Priority encoder

Find the lowest set bit: index plus a valid flag.

When to use it

Given a bunch of request lines, which one do you service? A priority encoder returns the index of the lowest set bit plus a valid flag, the building block of interrupt controllers, allocators and fixed-priority arbiters.

How it works

Scan the bits from high to low and keep the index of each one that's set; the last one written wins, so you end up with the lowest. valid is just the OR of all the inputs (is anything requesting at all?). A synthesizer maps this to a small tree of gates.

Gotchas

Try it

Runs on our simulator, edit the code and press Run to see the waveform.

Open & fork in the playground → Ship the verified version: lfpga add lfpga_priority_encoder

The runnable example above is a teaching version. The libfpga library ships a hardened, parameterised, CI-tested module (lfpga_priority_encoder) for production use.

Next recipe: Barrel shifter