Reputation: 41
I wonder how I implement the 2-complements method for binary-aritmetics when the number that is subtracted is less than the other number. For instance - If I want to subtract 13 from 12 ... i.e 12 -13 = -1.
I have tried the following steps:
1) 12 to binary using 8 bits (0000 1100
)
2) -13 to binary using 2-complements:
a) 13 into binary using 8 bits: 0000 1101
b) invert: 1111 0010
c) add 1: 1111 0010 + 1 = 1111 0011
So if I calculated correctly the result (1111 0011
) represents -13. So lets add this negative representation with 12:
00001100 + 11110011 = 11111111
So I do not understand the result - only only ones:s (1111...
)
This happens when the result is negative. Obviously I missed something.
Grateful for help!!!!
Upvotes: 2
Views: 228
Reputation: 3970
Congratulations, you've just discovered the difference between signed/unsigned integer representations!
Let's take, for example, the Uint16
format (unsigned 16 bit). It can represent any integer value from 0 (binary 0000000000000000
) to 65535 (binary (1111111111111111
).
So, what happens when you add one to 65535? You'll need another Uint16 to express that value, and the first will be all zeroes again:
0000000000000001
0000000000000000
Now, the signed version of Uint16, Int16
, may range from −32,768 to 32,767. Why? Because it may use its most significant bit to determine the signal.
Like this, for Int8
(signed integer, 8 bits), which happens to be exactly the format you're using on your example:
00000000 -> 0
00000001 -> 1
00000010 -> 2
[...]
01111110 -> 126
01111111 -> 127
10000000 -> -128 (MSB set - number is negative)
10000001 -> -127
10000010 -> -126
[...]
11111110 -> -2
11111111 -> -1 <- (This is your result!)
Notice that you're already taking that into consideration when you do step B - by inverting you're setting the MSB to 1, thus indicating that the value is negative.
What's happening to your calculations is that you'll reach a state of arithmetic overflow if you don't take into consideration the signal bit.
Here's some links that may help with your issue:
Bitwise Operator on positive and negative numbers
Signed number representations - Wikipedia
Integer (computer science) - Wikipedia
Upvotes: 2