Verilog signed unsigned operation

6.8k views Asked by At

I have referenced this ppt at 48page.

Q1. what if the signed addition operation have positive or negative overflow between (signed - signed) or (signed + signed), what should I do?

For instance, -63 + -96 , or 72 + 105 how to handle of these?

Q2. I found like this code from here.

reg signed [7:0] a;
reg [7:0] b;

initial
begin
result = a;            //Signed
result = a * a;        //Signed
result = a * 10;       //Signed
result = $unsigned(a); //Unsigned
result = a[0];         //Unsigned
result = a[7:0];       //Unsigned
result = {a,a};        //Unsigned
result = {10{a}};      //Unsigned
result = a + b;        //Unsigned
result = a * b;        //Unsigned
end

is this true?

1

There are 1 answers

0
Morgan On BEST ANSWER

Questions are best asked individually, so that the best answer for each part can be accepted.

Emman posted a link to a previous answer of mine i think that it is relevant to the first part of the question as it shows how to detect overflow and underflow.

As dave_59 has mentioned limiting based on overflow/underflow or allowing wrapping depends entirely on the arithmetic required. for some operations you know that and overflow will be brought back in range by the next operation so you have the effect of extended precision with out requiring the hardware. Typically in an integrator (Accumulating values) which is then differentiated (or is it the other way around?).

In most of my work I require limiting, Once you have detected limiting it is just a case of assigning the max, min or actual value.

 always @* begin
   if (overflow) begin
     result = {1'b0, {WIDTH-1{1'b1}}; //MAX +ve
   end
   else if (underflow) begin
     result = {1'b1, {WIDTH-1{1'b0}}; // MAX -ve
   end
   else begin
     result = the_real_result;
   end
 end

With regards your questions on signed/unsigned arithmetic they look correct but an easy way to check is set a to a negative value and run a simulation using $display("%d", variable_x); to see the value type of arithmetic.

NB: Verilog prefers unsigned arithmetic and will jump at the chance to do it. All operands have to be signed for signed arithmetic.