Encoder
An encoder converts one active input among many into a compact binary code identifying which input was active.
What it does
An encoder is the inverse of a decoder. It has 2^n inputs and n outputs. When exactly one input is high, the outputs give the binary index of that input. A 4-to-2 encoder turns four input lines into a two-bit code.
The ambiguity problem
A plain encoder assumes only one input is active at a time. If two inputs are high at once the output is meaningless, and if no input is high the output looks like input 0. Both cases need extra handling.
Priority encoder
A priority encoder resolves multiple active inputs by outputting the code of the highest-numbered active input and ignoring the rest. It usually adds a valid output that is high only when at least one input is active, distinguishing genuine input 0 from no input.
Uses
Priority encoders arbitrate interrupts, choosing the highest-priority pending request, and appear in floating-point hardware to find the position of the leading one during normalization.
In code
def priority_encode(inputs): # MSB has priority
for i in range(len(inputs)-1, -1, -1):
if inputs[i]:
return i, 1 # index, valid
return 0, 0