Design a priority encoder for req[7:0].
req[7], then req[6], … down to req[0].code[2:0] is the index of the highest asserted bit.code = 3'b000.Requirements
priority_encoder8req[7:0]code[2:0]
Examples
| req[7:0] | Description | code[2:0] |
|---|---|---|
8'b0000_0000 | No request active | 3'b000 |
8'b0000_0001 | Only req[0] active (lowest priority) | 3'b000 |
8'b0000_0100 | Only req[2] active | 3'b010 |
8'b0010_0100 | req[5] and req[2] active → req[5] wins | 3'b101 |
8'b1100_0000 | req[7] and req[6] active → req[7] wins | 3'b111 |
8'b0101_1010 | Multiple set, highest = req[6] | 3'b110 |
Syntax:
if (expression)
statement;
else if (expression)
statement;
else
statement;
Key Rules
expression must evaluate to a 1-bit result (0, 1, x, z).else, no action occurs.Common Uses
always @(*).Guidelines
else or default) to avoid unintended latch inference.begin…end for multiple statements.case for parallel decisions; if-else is better for priority logic.Example
always @(*) begin
if (sel == 2'b00) y = a;
else if (sel == 2'b01) y = b;
else if (sel == 2'b10) y = c;
else y = d; // avoids latch
end
General Syntax:
case (expression)
value1: statement;
value2: statement;
...
default: statement;
endcase
x/z).casez (opcode)
4'b1???: alu_op = ADD;
4'b01??: alu_op = SUB;
default: alu_op = NOP;
endcase
default to prevent latches.casez is preferred over casex in synthesizable RTL.Syntax:
for (init; condition; step) statement;
Rules
integer i;).Example
integer i;
always @(*) begin
sum = 0;
for (i=0; i<8; i=i+1) begin
sum = sum + data[i];
end
end
Guidelines
for loops to describe repeated hardware structures (not like software loops).forever and while are also allowed.