What is the result (in 8-bit binary) of adding the two 8-bit two's complement numbers 10111011 and 11010101 and how would you go about calculating that?
2 Answers
This is probably something any decent programming calculator can tell you but, assuming it wraps at eight bits, this is the result.
[ hex,unsigned,signed]
10111011 [0xBB, 187, -69]
+ 11010101 [0xD5, 213, -43]
--------
= (1)10010000 [0x90, 144, -112]
You can do this process manually as follows:
set carry to zero
for each position starting at right side, progressing left:
set sum to carry
add bit from position in first number to sum
add bit from position in second number to sum
if sum is greater than one:
subtract two from sum
set carry to one
else
set carry to zero
end if
store sum to position of result
end for
3 Comments
carry into result[0] is wrong. And, if your bits are 1 thru 8, the presence of result[0] means you have nine bits, not eight. Usually what happens is the result will wrap around and the final value in carry will indicate this.The nice thing about two's complement is that you don't need to know whether you have signed or unsigned numbers. Just take the binary representation, add, and discard the overflow bit. If you've left the range of representable numbers, well, tough luck. But adding two negative numbers and getting a positive one should raise suspicion.
On a practical note: Do not try to guard against overflow in C by asking things like
a = b+c;
if (((b > 0) && (a < c)) || ((b < 0) && (a > c))) {
...
}
This would probably work in standard debug builds, but C (and C++) compilers are allowed to optimize this check away. (It is more often seen for unsigned arithmetic, if (a >= (a+b)) { ... }, and gcc -Wall will warn that it knows that to be false. Which is fine, since the C standard says that overflow is undefined behavior anyway.)
I don't know what the situation is like in other languages with limited-range integer types.