Reputation: 99
Finding 2's complement.
If a number is positive, then its representation is same as that of its signed repesentation
0101 +5 0110 +6 0111 +7
If a number is negative, we convert first take one's complement of its signed representation and add one to it.
Like for -7 it is 0111+1=1000
for -128 it is one's complement of +128 and add one to it.signed representation of +128 is 010000000 (first zero is for sign). its ones complement is 101111111. adding one to i t gives 110000000 which is a nine bit numbers.
Hence we cannot store -128 in two's complement form????
Upvotes: 1
Views: 806
Reputation: 361585
An 8-bit value can represent the values 0-255 unsigned or -128 to +127 signed.
That is the two's complement representation of -128. Notice how -128's representation is identical to +128's. This is why signed bytes can only hold up to +127. By convention it was decided to interpret 1000 0000 as -128 rather than +128. It was a sensible decision because it lets us think of the leftmost bit as a sign bit (1 for negative, 0 for non-negative).
Now you didn't say anything about 8 bits, so you're probably wondering why I said to drop the leading 0. You don't have to.
The thing about negative numbers is that they don't really have "a" sign bit. They have a lot of them. An infinite number of them. The computer can only hold so many bits, but conceptually speaking negative numbers have an infinite string of 1's to the left.
Let's see what I mean by doing the same thing as above but in a 16-bit context.
Notice how the 16-bit representation of -128 (1111 1111 1000 0000) is the same as the 8-bit representation (1000 0000) except it has a bunch of 1's on the left. This is known as sign extension. Negative numbers are sign extended with extra 1's if you make them wider. Non-negative numbers are extended with extra 0's.
| 8-bit | 16-bit
----------------------|--------------------
+128 | 1000 0000 | 0000 0000 1000 0000
-128 | 1000 1000 | 1111 1111 1000 0000
This means that calling the leftmost bit the "sign bit" is a bit of oversimplification. If it were a sign bit you could just flip it to change a positive number to negative. That's how signed magnitude works. It's not how two's complement works. When you negate a number in two's complement you often end up flipping a whole bunch of bits on the left.
Upvotes: 2