I am a beginner at verilog and encountered this problem:
Assume that you have two 8-bit 2's complement numbers,
a[7:0]
andb[7:0]
. These numbers are added to produces[7:0]
. Compute whether a (signed) overflow has occurred.
Now my answer to the asked value of overflow was
assign overflow = ~(s[7]&a[7]&b[7]);
While the correct answer shown was
assign overflow= (~s[7]&a[7]&b[7])|(s[7]&(~a[7])&(~b[7]));
I want to know where I went wrong.
-
1\$\begingroup\$ Usually taken as the XOR of the carry-out of the b[6] adder and the carry-out of the b[7] adder. \$\endgroup\$jonk– jonk2020年01月15日 13:34:14 +00:00Commented Jan 15, 2020 at 13:34
3 Answers 3
Signed overflow occurs when the result of addition is too large for a given type to represent.
This occurs when either:
- Addition of two positive integers result in a negative integer result (so the result msb - the sign bit - is 1 when it should be zero)
or
- Addition of two negative integers result in a positive integer result (so the result msb is 0 when it should be 1).
For each condition, we would then have:
(Positive integers input)
s[7] would be '1' for a[7] and b[7] both being '0' given by (s[7]
[1 if result is negative] & (~a[7])
[result is 1 if input was positive] & (~b7))
[result 1 if input was positive]; the logical and would show that two positive inputs resulted in a negative output.
(Negative integers input)
Overflow occurs if we have a positive result, so:
s[7] would be zero for a[7] and b[7] both being 1. This is given by (~s[7]
[result is 1 if positive result] &a[7]
[would be 1 for negative input] &b[7])
[would be 1 for negative input. if all these bits evaluate 1, overflow has occurred.
Your assignment captures the negative input case and not the positive input case where the quoted answer captures both.
assign overflow = (a[7]^b[7]) ? 0: (s[7]^a[7]);
This is my answer. It shows correct. Wish it helps.
Declarations:
`define n 7 // number of bits - 1
logic [`n:0] a; // input a
logic [`n:0] b; // input b
logic [`n:0] s; // sum
logic [`n:0] d; // difference
logic overflow; // overflow/underflow detection
Addition overflow:
s = a + b
overflow = ~(a[`n] ^ b[`n]) & (a[`n] ^ s[`n])
Subtraction overflow:
d = a - b
overflow = (a[`n] ^ b[`n]) & (a[`n] ^ d[`n])