Search code examples
verilog

How to convert Signed Binary to Integer in Verilog?


I am trying to convert signed binary numbers to integer in verilog for synthesis to display, I have a couple of questions. Below is my code,

.....
if(acc[i][j]>10)               //acc is a 2d register

begin
  m_reg <= j-const_10;        // const_10 is 16'b0000000000001010
  m_int <= m_reg;              
  $display("Current value of M(bits)=%b",m_reg);
  $display("Current value of M(int)=%d",m_int);
end
else
....
  1. j can be less than 10, meaning m_reg can be negative. In that case, I am assuming m_reg will give me a signed binary negative number.

  2. If it does, how do I convert it to an integer to display because I guess m_int = m_reg will give me only unsigned.


Solution

  • All data is 'binary' when displaying we have the choice of visualising in binary, decimal of hexadecimal. When inputing data we have the same choice but what is set and stored remains the same.

    These are all the same:

    a = 4'b1111;
    a = 4'd15;
    a = 4'hf;
    

    To display in the given format:

    $display("Binary  %b", a);
    $display("Decimal %d", a);
    $display("Hex     %h", a);
    

    Leading 0's are not displayed, at least for decimal so min widths can be used.

    $display("min of 2 Decimal   %2d", a);
    

    Dealing with signed numbers: declare the reg, logic or wire as signed, or convert when displaying.

    reg        [3:0] a;
    reg signed [3:0] a_s;
    
    initial begin
      a   = 4'b1111; // is this 15 or -1 depends on if you read as signed
      a_s = 4'b1111; // -1
      #1ns;
      $display("Decimal converted to signed %d", $signed(a));
      $display("Signed Decimal              %d", a_s);
    end