Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I sign extend in SystemVerilog?

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?

like image 618
Josh S. Avatar asked Dec 24 '22 08:12

Josh S.


2 Answers

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.

like image 52
dave_59 Avatar answered Feb 24 '23 21:02

dave_59


Few things you need to take care is,

  1. you haven't declared a data type for in and out, so by default they are wire and wire can't be used at LHS inside procedural block. Refer Section 6.5 Nets and variables (SV LRM 1800-2012). So either use a continuous assignment or declare it as a variable (i.e. reg/logic etc.).

  2. The assignment of unpacked array is illegal in your example, so either use packed array or follow the instructions given in Section 10.10 Unpacked array concatenation (SV LRM 1800-2012)

like image 25
H.Modh Avatar answered Feb 24 '23 21:02

H.Modh