I'm trying to do the following problem:
E8B2035D
-FB60528D
----------
In which, the integers represented are hex representations of 32-bit two's compliment binary numbers. What is the best approach to solve this problem, and detect overflow?
Subtraction becomes addition when you use two's complement. So I would take the complement of the second number, then add them:
As you know, the two's complement of a number starts out by turning every 1 into 0 and vice versa (handy rule of thumb: do 15 - number, so F -> 0, E -> 1, D -> 2, etc):
FB60528D --> 049FAD72
Then add one to the number (in this case, 2 + 1 = 3
, and there is no carry):
049FAD73 -- the two's complement of FB60528D
Now we add the numbers, using conventional rules of addition:
E8B2035D
049FAD73 +
----------
D + 3 = 10 : write 0, carry 1
1 + 5 + 7 : write D, carry 0
3 + D = 10 : write 0, carry 1
1 + 0 + A : write B, carry 0
2 + F : write 1, carry 1
1 + B + 9 : write 5, carry 1
1 + 8 + 4 : write D, carry 0
E + 0 : write E
The final result (still in two's complement) is
ED51B0D0
You would detect overflow if the last calculation resulted in a carry (a number > F
).