Computing Library › Classical Logic Gates
Classical Logic Gates

Encoder

An encoder compresses a one-hot set of inputs into a compact binary code, the inverse of a decoder.

What it does

An encoder takes 2 to the n input lines, of which one is active, and outputs the n-bit binary code of that line's position. It is the inverse of a decoder, turning a one-hot signal back into a number.

Four-to-two example

I0I1I2I3O1O0
100000
010001
001010
000111

The ambiguity problem

A plain encoder assumes exactly one input is active. If none are active, the all-zero output is indistinguishable from input zero, and if several are active the output is undefined. Real designs solve this with priority.

Priority encoder

In code

python

def priority_encoder(inputs):
    for i in reversed(range(len(inputs))):
        if inputs[i]:
            return i, 1   # code, valid
    return 0, 0            # nothing active

Where it appears

Encoders compress keypad and switch matrices into codes, resolve which interrupt source to service, and identify the highest set bit in a word. Paired with a decoder they form a compress-and-expand path for selection signals.