Encoders & Decoders

Decoders turn binary codes into one-hot outputs; encoders do the reverse. Learn n-to-2ⁿ decoders with enable, address decoding for memory, priority encoders, BCD-to-7-segment decoders, keypad encoding, and code converters (binary ↔ Gray, BCD).

Whenever a processor selects one memory chip or peripheral, a decoder turns address bits into chip-select lines. Keyboards and interrupt controllers use priority encoders to report which input is active.

An analogy

A decoder is like a hotel receptionist reading a room number and pointing you to exactly one door; an encoder is the reverse — seeing which door is open and telling you its number.

Decoders

A 2-to-4 or 3-to-8 decoder (74HC138) activates exactly one output. Enables allow cascading (two 3-to-8 → 4-to-16). Active-low outputs are common in real chips.

Encoders

A simple encoder assumes only one input is active. A priority encoder (74HC148) outputs the index of the highest-priority active input plus a valid flag — used for interrupt priority and keypads.

Display and code converters

BCD-to-7-segment decoders drive digits. Gray code (one bit changes per step) is used in rotary encoders and FIFO pointers to avoid glitches when crossing clock domains.

Address decoding

Memory maps use high address bits to select devices. Full decoding uses all address bits (unique addresses); partial decoding is cheaper but creates aliases.

Formulas

Worked example: Binary to Gray

Given: B = 1011

Find: Gray code.

Answer: 1110

Worked example: Memory decoding

Given: 64 KB address space, 8 KB chips

Find: Decoder.

Answer: 74HC138 on A15–A13

3-to-8 decoder and 8-to-3 priority encoder

module dec3to8 (input [2:0] a, input en, output [7:0] y);
  assign y = en ? (8'b1 << a) : 8'b0;
endmodule

module prio_enc8 (input [7:0] req, output reg [2:0] code, output reg valid);
  integer i;
  always @* begin
    code = 3'd0; valid = 1'b0;
    for (i = 0; i < 8; i = i + 1)      // highest index wins
      if (req[i]) begin code = i[2:0]; valid = 1'b1; end
  end
endmodule

Shifting a 1 by the input value gives a one-hot decoder. The loop assigns the highest active request last, so it wins — a priority encoder.

Common mistakes

Applications

Key takeaways

Going further