How to sign-extend a number in Verilog

前端 未结 3 589
礼貌的吻别
礼貌的吻别 2021-02-08 00:51

I\'m working on a simple sign-extender in Verilog for a processor I\'m creating for Computer Architecture.

Here\'s what I\'ve got so far: [EDIT: Changed the selection st

相关标签:
3条回答
  • 2021-02-08 01:35

    We can use the syntax $signed to sign extend

    module signextender(
      input [7:0] unextended,//the msb bit is the sign bit
      input clk,
      output reg [15:0] extended 
    );
    
    always@(posedge clk)
      begin 
        extended <= $signed(unextended);
      end
    endmodule
    
    0 讨论(0)
  • 2021-02-08 01:44

    You nearly got it...

    always @( posedge clk ) begin
        extended[15:0] <= { {8{extend[7]}}, extend[7:0] };
    end
    

    You're also missing a clock edge for the '40' test. Try this, & let me know how you get on...

    0 讨论(0)
  • 2021-02-08 01:46

    By the way your module assign is pure combinational so it should not contain a clk, this is another way of doing your module:

    module sign_ext
                 (
                  unextend,
                  extended
                 );
    
    input  [15:0] unextend;
    output [31:0] extended;
    
    assign extended = {{16{unextend[15]}}, unextend};
    
    endmodule
    
    //TB
    
    module tb_sign_ext;
    
    reg  [15:0] unex;
    wire   [31:0] ext;
    
    sign_ext TBSIGNEXT
                      (
                       .unextend(unex),
                       .extended(ext)
                      );
    
    initial
    begin
       unex = 16'd0;
    end
    
    
    initial 
    begin
       #10 unex = 16'b0000_0000_1111_1111;
       #20 unex = 16'b1000_0000_1111_1111;
    end
    
    endmodule
    
    ;)
    
    0 讨论(0)
提交回复
热议问题