Two's Complement
Negative Numbers: Two's complement representation
So far, we've just used positive numbers. If you have tried the last
part of lab one yet, you have seen that the result is a negative number.
Does the AVR CPU know this? How do we know this? In lab 1 it is easy
because we can do the arithmetic by hand and see that a negative answer
is correct, but if we don't know ahead of time, how do we know when we
are programming?
In writing, we use a minus sign to indicate a negative number. But the
CPU and memory just know 1's and 0's, that is all. So how do we
determine a negative number.
All of the values in a computer are of some fixed length of bits. In an AVR CPU, most are 8 bits, and some are 16 bits. But we always know this. This is important: values are always a fixed number of bits.
An ingenious representation of signed numbers: the 2's complement representation (2C)
Take the positive binary number, complement (flip to opposite) all the bits, then add one
Thus, decimal -11 is found by:
- taking positive decimal 11, which is 00001011
- complementing it, which gives us 11110100 (each bit is opposite)
- then adding 1, which gives us 11110101
- so, decimal -11 is 8-bit binary 11110101
In 2C the upper bit acts as a sign bit: a leftmost 1 means negative, a leftmost 0 means positive
But arithmetic can be done completely ignoring whether a number is signed or not.
That means (important): the CPU doesn't care if you are using signed numbers or unsigned numbers!
Another representation is 1's complement, which is just complementing all the bits (and not adding one like 2C does).
- One wierd thing about 1C is that it has two zero's -- a positive zero (00000000) and a negative zero (11111111).
- Some historical computers were built that used 1C, but today all use 2C.