HDLbits
Start Practicing

Verilog Language/Procedures

Priority Encoder (if/else)

medium
proceduresalways-blockif-elsepriority-encoder

Procedural blocks (always @(*) for combinational logic) let you describe behavior using imperative constructs like if/else, unlike continuous assignments. A priority encoder is a natural example: it reports the position of the highest-priority active input, and cascaded if/else naturally expresses “priority”.

Build a circuit with a 4-bit input in and a 2-bit output pos. pos should hold the index of the most-significant bit of in that is set to 1. If in is all zeros, pos should be 0.

Interface

Signal Direction Width Description
in input 4 Input bits, priority is in[3] highest, in[0] lowest
pos output 2 Index of highest-priority set bit (0 if in == 0)

Examples

in pos Reasoning
4'b0000 0 No bits set, default to 0
4'b0001 0 Only bit 0 set
4'b0110 2 Bit 2 is the highest set bit
4'b1111 3 Bit 3 is the highest set bit

Notes

  • Use always @(*) for a combinational block, and declare pos as output reg (procedural assignments require a reg-type target in Verilog).
  • Check in[3] first, then in[2], then in[1]: whichever is 1 first “wins” thanks to the if/else if chain.