4-to-2 Priority Encoder

Easy

Problem Statement

Implement a 4-to-2 priority encoder. Ports: - `in` — input, 4 bits (`in[3:0]`) — four independent request lines; any number of them may be asserted simultaneously - `code` — output, 2 bits (`code[1:0]`) — encoded index of the highest-priority asserted input - `valid` — output, 1 bit — asserted (1) whenever at least one input bit is 1, and 0 only when all inputs are 0 Priority order: `in[3]` has the highest priority, `in[0]` has the lowest. Exactly: - If `in[3] = 1`: `code = 2'b11`, `valid = 1` (regardless of `in[2:0]`). - Else if `in[2] = 1`: `code = 2'b10`, `valid = 1`. - Else if `in[1] = 1`: `code = 2'b01`, `valid = 1`. - Else if `in[0] = 1`: `code = 2'b00`, `valid = 1`. - Else (`in = 4'b0000`): `code = 2'b00`, `valid = 0`. This is a purely combinational circuit — `code` and `valid` must respond immediately to any change on `in`. There is no clock and no internal state.

Verilog