Safe Case Decoding
Part of the RTL Design & Verification section of Coddy's Verilog journey. Lesson 4 of 38.
Use an ordinary case statement for exact control codes. Supply default behavior for unsupported codes and assign all outputs. Wildcard decoding with casex can hide unknown control bits in simulation, so it is unsuitable when unknowns should remain visible during debugging.
Relevant excerpt; surrounding declarations and connections are supplied in the challenge.
always @* begin
y = 0;
invalid = 0;
case (op)
0: y = a & b;
1: y = a | b;
default: invalid = 1;
endcase
endUnsupported codes produce an explicit status rather than retaining a previous output.
Define unsupported control codes explicitly and avoid masking unknown controls with casex.
Challenge
MediumImplement an 8-bit logic unit: op 0 computes a AND b, op 1 computes a OR b, op 2 computes a XOR b, and op 3 returns zero with invalid set to one. invalid is zero for supported operations. Output columns: y, invalid. All stimulus values are known binary values.
Complete design.v and preserve its module names and ports. The locked testbench.v supplies input changes and prints the outputs after they settle. It chooses a scenario using a simulator argument such as +CASE=1; no standard input is required. Do not add printing, delays or simulation termination to the design. Expected output is one row of decimal values per observation, separated by one space and ending with a newline.
Try it yourself
module dut (input [1:0] op, input [7:0] a, input [7:0] b, output reg [7:0] y, output reg invalid);
// Replace this placeholder with your design.
initial y = 0;
initial invalid = 0;
endmoduleThis lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in RTL Design & Verification
1Reliable Combinational RTL
Defaults Prevent LatchesPriority EncodersOne-Hot ValidationSafe Case DecodingRecap - Request RouterPractice on your own: Online Verilog compiler