问题
I have basic binary math question. For example;
reg [31:0] a = 32'hFFFF_FFFF;
reg [31:0] b = 32'hFFFF_FFFF;
reg [31:0] c = 0;
I know c = a - b will result in zero and overflow flag will not be set.
My understanding is that ALU uses 2's complement of subtrahend (right side of operator) and adds it to minuend (left side of operator).
So 2s complement for value stored in reg b is 32'h1. Now, if I add this to reg a, I will get 32 zeros and a 1, which is overflow. Then why is not overflow flag set?
Even if I change width of reg c to 33, c[32] is not set to 1. I understand that when two equal numbers are subtracted, there is no overflow but I get an overflow when I do 2s complement math.
Let help me clear this confusion in my head. Thank you for your time.
回答1:
a
, b
, and c
are all 32-bit unsigned variables, and you are performing 32-bit arithmetic. The LRM says the resulting width of an arithmetic operation is the width of its largest operand. So the overflow or 33rd bit is truncated. That fact remains true even when extending c
to 33 bits.
回答2:
you have to look at what two's complement is. So, in your example a
and b
are 32-bit vectors with all bits set to '1':
a[31:0] = 32'hFFFF_FFFF;
two's complement of this is 32'h0000_0001; so, adding it to b
will cause all set to 0
and overflow bit 33
truncated because the width of the operation is 32 bits.
Now, supposedly you have a 33 bit vector
a[32:0] = 33'hFFFF_FFFF;
the two's complement will be 33'h1_OOOO_OOO1
. So, if you add it to a 33-bit vector 33'hFFFF_FFFF
, you will still have all 33 bits equal to '0'. If you add more bits to a
, more 1
be added to the msb side: 34'h3_0000_0001
, ...
And, if c
is wider than operation context, it will always be 0-extended, for unsigned vars, otherwise sign-extended.
As a result, you will always end up in the situation when the overflow bit is outside of the operation width, and is truncated. This is guaranteed by LRM requirement of the operation width.
来源:https://stackoverflow.com/questions/50125937/why-is-there-no-overflow-flag-set-for-binary-subtraction