r/AskComputerScience • u/scarcelyberries • Aug 26 '25
Adding with 2s complement
I'm learning to add with 2s complement, and I think I have it down for the most part but there's something still tripping me up. I'm using 6-bits.
When I add -25 and -8, I get
1011111 which seems correct as is and has a leading 1 to show negative, but overflows my 6 bits
When I add +25 and -8, I get
011001 for 25 and for 8 I have 001000, flip and add 1 for 110111 into 111000
Then when I add 011001 and 111000 I get 1010001 instead of the expected 010001. Why does the overflow on this one make it a different number? Why does it not lead with a zero? Am I missing something? I feel like I'm skipping something important but don't know what
Please help, I've been looking at this and googling for an hour and haven't found an explanation
View all comments
Show parent comment
1
u/johndcochran Aug 27 '25 edited Aug 29 '25
Overflow detection is slightly more complicated. Basically, you look at the carry in and the carry out to the most significant bit. If they differ, then you have a signed overflow. To illustrate:
Notice that the carry in to the MSB is 0, while the carry out is 1. They are different and hence you have a signed overflow.
In this case, there was a carry in to the MSB of 1 and a carry out of 1, so there's no overflow.
Another example:
And here, we have a carry in of 1 and a carry out of 0. So, we have another overflow.
One trick to determine what the carries out is to use the exclusive OR function on both operands and the sum. For example:
The 001110 indicates that bits 1,2,3 had carries from the lower numbered bits. To illustrate, using your -25 and -8 example, you have:
And since an overflow is detected IFF the carry in the MSB differs from the carry out from the MSB, you can easily shift the XOR result and XOR it against the shifted value. So