Unsigned Binary Integers⟹ the normal representation
An n-bit number:
x=xn−12n−1+xn−22n−2+⋯+x121+x020
Has a term up to 2n−1
Has a range: 0 to (2n−1)
Example:
(11)10=0x0000000B
(11)10=000000000000000000000000000010112
(11)10=0+⋯+1×23+0×22+1×21+1×20
(11)10=0+⋯+8+0+2+1
If we had 32 bits, then we could represent the numbers 0 to +4,294,967,295
Signed Binary Integers
So the question is probably: "How do we encode a Negative integer?"
Well, we have two methods:
One's Complement
Two's Complement
One's Complement
The Leading Bit (the one on the far left) decides if the integer is negative or not: 1 = Negative
All positive numbers have the same representation as unsigned.
Get the Value of a Negative Number by inverting all bits then multiply by -1
Example:
(0101)2=(0101)2=5
(1101)2=−1×(0010)2=−2
(0000)2=(0000)2=0
(1111)2=−1×(0000)2=−0???? So it does not deal with overflow
So it's pretty obvious that one's complement is rarely used!
Two's Complement
The Leading Bit (the one on the far left) decides if the integer is negative or not: 1 = Negative
If a number is non-negative (so 0 is included), then same representation as unsigned, otherwise:
You invert the leading bit, read the expansion as a non-negative integer and add −2n, ignoring any overflow
The n in −2n is the exponent on the 2. So in (1101)2, the leading bit = 1 so its a negative number. That leading bit is the 3th bit because →231221210201 so n=3
Example:
(0101)2=(0101)2=5
(1101)2=(0101)2−23=5−8=−3
(0000)2=(0000)2=0
(1111)2=(0111)2−23=7−8=−1
Advantages:
Arithmetic is the same whether positive or negative:
(0101)2+(1101)2(0010)2=5=−3=2
No signed 0
One extra value is represented with the same number of bits
For an n-bit number:
Range of values is from −2n−1 to 2n−1−1
Same bits, but different numbers
It is important to realize that the same bit sequence can represent different numbers
(10011010)2⟹(154)10interpretted as unsigned⟹(−102)10interpretted as two’s complement
This can clearly be a problem when programming!
unsignedint a = (1 << 31); // a = 2147483648 (unsigned)int b = a; // b = -2147483648 (signed)
Computing the opposite (signed negation)
In two's compliment, sometimes we want to find the negative representation of a binary number.
Let's say we have the number 6. We know that this is (0110)2 in binary. But what is -6 in binary?
We can get the bit-wise complement and then add 1 to it: