Prev Problem
Next Problem

51. Opcode Decoder

module alu_decoder (
    input  [1:0] opcode,
    output reg [3:0] alu_op
);
    always @* begin
        case (opcode)
            2'b00: alu_op = 4'b0001;
            2'b01: alu_op = 4'b0010;
            2'b10: alu_op = 4'b0100;
            2'b11: alu_op = 4'b1000;
            default: alu_op = 4'b0000;
        endcase
    end
endmodule

💡Remember

  • if–else = priority (first true wins). case = parallel decode (exact match).
  • Always include a default (or final else) to avoid latches.
  • For decoders/opcodes/FSM state → prefer case (flatter, faster).
  • case is more readable than long if–else chains, especially when checking multiple exclusive values.
  • Synthesis tools map case directly to efficient decoder hardware, while if–else infers cascaded multiplexers (slower and larger).
  • Using case makes intent clear: you want one-hot decode, not priority logic.