← ProblemsVerilog Language / Procedures

Priority encoder

36%proceduresconditionals

A priority encoder reports the position of the first 1 bit in its input.

Build a 4-bit priority encoder: pos is the index of the lowest-numbered input bit that is 1. If in is all zeros, output pos = 0.

Examples:

in = 4'b0000  ->  pos = 0   (no bits set)
in = 4'b0001  ->  pos = 0
in = 4'b1010  ->  pos = 1   (bit 1 is the lowest 1)
in = 4'b1100  ->  pos = 2
in = 4'b1000  ->  pos = 3

A case with all 16 input values works, but a casez with don't-care bits — or a chain of if/else — is much shorter.