1

I have a 16-bit number which might be x (i.e. unknown).
I would like to zero-extend the number to 32 bits, but if the MSB is x, then I would like it to be x-extended instead of zero-extended. (This helps with my simulation.)

How can I do this?

2 Answers 2

6

Unless you are working with signed values, I think you will need a custom function for this. If you are working with signed values, the MSB will be X-extended on an assignment from a 16-bit value to a 32-bit value if the sign bit is X. However if the MSB (the sign bit) is a 1 then it will be 1-extended, which is most likely not what you want if you are working with unsigned values.

Here's a simple function to do this.

function [31:0] extend(input[15:0] in);
begin
   if (in[15] === 1'bX) begin
      extend = {16'hXXXX, in};
   end else begin
      extend = {16'h0000, in};
   end
end
endfunction

Example:

$display("%032b", extend(16'h0000));
$display("%032b", extend(16'hFFFF));
$display("%032b", extend(16'bX000_0000_0000_0000));

Output:

00000000000000000000000000000000
00000000000000001111111111111111
xxxxxxxxxxxxxxxxx000000000000000
3
  • You can also avoid the if/else and just say 'extend = { {16{in[15}}, in};' Avoids unecessary control flow statements which I think is almost always a win in Verilog since it more closely models what you're actually building. Commented Mar 19, 2013 at 13:07
  • 1
    @BrianMagnuson That's a nice suggestion but I think the OP wanted to zero extend even if bit 15 was a 1. What you have would extend with 1's in that case.
    – dwikle
    Commented Mar 19, 2013 at 15:02
  • 1
    Ah, you're right. I suppose you could make the first part of the concatination {16{in[15] & 1'b1}}. That's starting to get a bit obfuscated though. Commented Mar 19, 2013 at 18:21
2

If your simulator is modern enough to support SystemVerilog syntax:

module tb;

reg [15:0] a;
reg [31:0] b;

initial begin
    $monitor("a='b%b b='b%b", a, b);
    #5 a= '1; extendo();
    #5 a= '0; extendo();
    #5 a= 'z; extendo();
end

task extendo;
    b[15:0] = a[15:0];
    b[31:16] = (a[15] === 1'bx) ? 'x : '0;
endtask

endmodule

Output:

a='bxxxxxxxxxxxxxxxx b='bxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
a='b1111111111111111 b='b00000000000000001111111111111111
a='b0000000000000000 b='b00000000000000000000000000000000
a='bzzzzzzzzzzzzzzzz b='b0000000000000000zzzzzzzzzzzzzzzz

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.