I'm trying to understand these illustrations but there are parts which I don't understand:
"But the computer had to count backwards for the negative numbers"
- Why does adding a 1 to the front of a binary mean the computer has to count backwards?
"Flip the bits and add开发者_高级运维 1!"
- What does that mean add 1?
woops: http://csillustrated.berkeley.edu/PDFs/integer-representations.pdf
This may be easiest to show by example. Here are the numbers from -4 to 4 represented in binary:
4 0000 0100
3 0000 0011
2 0000 0010
1 0000 0001
0 0000 0000
-1 1111 1111
-2 1111 1110
-3 1111 1101
-4 1111 1100
So say we want to go from 1 to -1. We first flip all the bits of 1
1 0000 0001
flip bits
-----------
1111 1110
Then we add a 1:
1111 1110
+ 1
-----------
1111 1111
We now have -1.
I'm not seeing the illustrations, but you're probably talking about Two's complement representation. (http://en.wikipedia.org/wiki/Two's_complement)
Why does adding a 1 to the front mean the computer has to count backwards?
Due to how carrying works,
FFFFFFFFF + 1 == 0
and0 - 1 == FFFFFFFF
. All the bits get flipped, including the first bit. If you simply define the negative numbers as those starting with a 1 bit (80000000 - FFFFFFFF) then you get a nice uniform behavior for addition with a natural overflow.Flip the bits and add 1: in 2's complement, this negates a number
~x+1 == -x; // always true
What you're talking about is called signed integers.
精彩评论