← ProblemsVerilog Language / Procedures

Priority encoder with casez

36%proceduresconditionals

Same idea as the previous problem, scaled up: build an 8-bit priority encoder. pos is the index of the lowest-numbered bit of in that is 1; output 0 when no bits are set.

A plain case would need 256 arms. Use casez, where a z in a case pattern matches either 0 or 1 — then only nine arms (eight patterns plus a default) are needed:

in = 8'b00000000  ->  pos = 0
in = 8'b10010000  ->  pos = 4
in = 8'b00000011  ->  pos = 0

Note: casez arms are checked in order, and the first match wins — order your patterns so this works in your favor.