Difficulty: Medium · Puzzle 5 of 6 · Topic: Datatype and Bit Puzzles
Predict all four output lines exactly (including the case of the hex digit) and explain why `i` and `w` disagree about unknown data.
module p5;
logic [3:0] l = 4'b10x1;
int i = l;
logic [31:0] w = l;
initial begin
$display("i=%0d", i);
$display("w=%h", w);
$display("w==32'h9 -> %b", w == 32'h0000_0009);
$display("w===32'h9 -> %0d", w === 32'h0000_0009);
end
endmodule`int` is 2-state, but `logic [31:0]` is 4-state. Compare `==` versus `===` separately. For `%h`, think about how a hex digit that is only partly unknown is printed.
1) Assigning `l` into 2-state `int i` collapses x to 0, so `i` becomes 4'b1001 = 9.
2) Assigning to 4-state `w` preserves the unknown bit. The low nibble is 1,0,x,1: some bits known, some not, so `%h` prints an uppercase `X` for that digit (only an all-x nibble prints lowercase `x`), giving 0000000X.
3) `w == 9` returns x because the unknown bit takes part in logical equality and no known bit differs.
4) `w === 9` returns 0 because case equality requires an exact bit match and x does not equal 1.Answer: i=9 w=0000000X w==32'h9 -> x w===32'h9 -> 0
Checked by running the code in Icarus Verilog 13 and Verilator 5; the printed output supports the answer above. Icarus keeps the x in the 4-state logic vector and prints the partly unknown digit as X. Verilator is 2-state, so the x is lost on load and both compares give 1; this is why you need a 4-state tool for this puzzle.
Candidates memorize that X is preserved but forget that 2-state scalar types silently coerce it away, and in a 2-state simulator such as Verilator this program prints w=00000009 and both compares as 1, so run it on a 4-state tool.
What type change would keep `i` 32-bit wide but preserve X/Z information? Model answer: declare it `integer` (4-state, signed 32-bit) or `logic signed [31:0]`; then `i` keeps the x bit and `%0d` prints X.
I would first look at the type on the left, because a two-state int cannot hold an x, so it collapses to 0 and the value is 9. The four-state wire keeps the unknown bit and prints 0000000X with an uppercase X, because the nibble is only partly unknown. Equality gives x because the unknown bit blocks a decision, and case equality gives 0 because the x does not match a 1. The trap is that a two-state simulator like Verilator prints 00000009 and 1 for both compares, so I would run it on a four-state tool and check where else a two-state type hides an x.