How do I sign extend in SystemVerilog?

Josh S. picture Josh S. · Mar 3, 2016 · Viewed 16.2k times · Source

Below is the code I have for my module:

module sext(input in[3:0], output out[7:0]);

    always_comb
        begin
            if(in[3]==1'b0)
                assign out = {4'b0000,in};
            else
                assign out = {4'b1111,in};
        end

endmodule

For some reason this is not working. Instead of sign extending it is zero extending. Any ideas to why this might be the case?

Answer

dave_59 picture dave_59 · Mar 3, 2016

I'm going to assume you meant (input [3:0] in, output [7:0] out). If that is true, then all you needed to write is

module sext(input signed [3:0] in, output signed [7:0] out);

    assign out = in;

endmodule

You could also write

module sext(input [3:0] in, output [7:0] out);

    assign out = 8'(signed'(in));

endmodule

And perhaps you don't even need to write this as a separate module.