Reputation: 1
I'm trying to figure it out but still stuck.
Let's say we have the decimal number 13 (1101 in binary). At unsigned, we need minimum 4 bits to represent it (1101 as it is) but in 2's complement signed do we need 5 bits with the MSbit set to 0 because 13 is a positive number? I know that in 2's complement, the MSbit indicates the sign of the value (+ or -). So it will be 01101? Also, if the MSbit is 0, the number is still the same in singed 2's complement but if it is 1 then is will be As = Au - 2^n.
Let's say now that the number is -13. To find out the binary form of -13, i flip all the bits of 13 (1's complement) and then add +1 to them (2's complement). So in this case we have: 1101 ---> 0010 + 1 ---> 0011
but in singed 2's complement the MSbit is 0 (so it's positive) and we say "this is the number 3" or can we 1 as the new MSbit to look like negative (like 11101)?
Thanks :)
Upvotes: 0
Views: 2344
Reputation: 81149
In two's-complement, positive numbers have an infinite number of leading zeroes, and negative numbers have an infinite number of leading ones. To allow storage in a finite space, the leftmost digit of a representation will be repeated infinitely far to the left. Since the number 13 needs to lead off with an infinite number of zeroes, its representation must start with a zero. The shortest representation would thus be 01101, but other representations with arbitrary numbers of zeroes (like 00001101 or 0000000000001101) would be just as valid.
Although it's possible to negate a number by flipping all the bits and adding 1, I think it's more helpful to simply subtract from zero. If one subtracts ...01101 from ...00000, the last digit will be 1 with a borrow, then 1 with a borrow, 0 with a borrow, 0 with a borrow, and 1 with a borrow. Since all remaining digits in both the value being subtracted (...01101) and the value being subtracted from (...00000) will be zeroes, every remaining digit in the result will be a 1 with a borrow.
Upvotes: 1
Reputation:
Let's say now that the number is -13. To find out the binary form of -13, i flip all the bits of 13 (1's complement) and then add +1 to them (2's complement). So in this case we have: 1101 ---> 0010 + 1 ---> 0011
You didn't flip all the bits, because negating a number implies using signed representations. You give the bits representing 13 as 1101b
, which is not signed. If it were signed, it would represent another number, namely 101b
+ 1 = 110b
= 6, hence -6.
You must ensure, that a positive number, such as 13, does indeed have a 0 as its MSB, exactly as you have shown to be in its minimal form: 01101b
. Swapping these you obtain 10010b
, adding 1 then yields 10011b
, which in your 5-bit-bytes does indeed represent -13.
Using the more common 8-bit byte, you would find 11110011
for the negative value and 00001101
for the positive. (Note, that flipping all bits and adding 1 is used in both directions.)
Upvotes: 0