Difficulty: Medium · Puzzle 3 of 6 · Topic: Datatype and Bit Puzzles
Predict `a`, `b`, and `c`. Why are `b` and `c` different from `a`?
module p3;
logic [7:0] u8 = 8'h80;
logic signed [15:0] a, b, c;
initial begin
a = u8;
b = signed'(u8);
c = $signed(u8);
$display("a=%0d b=%0d c=%0d", a, b, c);
end
endmoduleAssignment from unsigned extends with zeros. `signed'(...)` and `$signed(...)` reinterpret source sign first, then assignment extends.
1) `a = u8` zero-extends 8'h80 into 16'h0080, which is +128.
2) `signed'(u8)` treats the 8-bit pattern as signed before assignment, so 8'h80 is -128 and sign-extends to 16'hFF80.
3) `$signed(u8)` has the same signed reinterpretation effect here, so `c` is also -128.Answer: a=128, b=-128, c=-128
Checked by running the code in Icarus Verilog 13 and Verilator 5; the printed output supports the answer above. The signedness of the right-hand side decides sign extension. (Icarus, 4-state) The signedness of the right-hand side decides sign extension. (Verilator, 2-state)
The signedness of the destination does not decide the extension: the signedness of the right-hand expression does, so `a = u8` zero-extends even though `a` is signed.
What value would `b` have if `u8` were `8'h7F` instead? Model answer: 127, because the sign bit is 0 and sign extension adds zeros, identical to zero extension.
I would ask what the right-hand expression is, because its signedness, not the destination, decides the extension. Plain assignment of the unsigned byte zero-extends, so I get 128, while the signed cast and the dollar signed both reinterpret the pattern as minus 128 and sign-extend. The trap is that the destination being signed does not help, since the extension is decided before the assignment. I would then check the case where the top bit is zero, where both forms agree.