Mr.Frag
Posts: 13410
Joined: 12/18/2002 From: Purgatory Status: offline
|
You sure you want more math? It only hurts more from here on. Unsigned integers: (0-15) 0 = 0000 1 = 0001 2 = 0010 3 = 0011 4 = 0100 5 = 0101 6 = 0110 7 = 0111 8 = 1000 9 = 1001 10 = 1010 11 = 1011 12 = 1100 13 = 1101 14 = 1110 15 = 1111 In twos complement, the leftmost bit becomes the sign of the number (0 for positives, 1 for negatives) Signed Integers (-8 to +7) 0 = 0000 1 = 0001 2 = 0010 3 = 0011 4 = 0100 5 = 0101 6 = 0110 7 = 0111 -8 = 1000 -7 = 1001 -6= 1010 -5 = 1011 -4 = 1100 -3 = 1101 -2 = 1110 -1 = 1111 To convert a negative, one applies the twos complement and adds 1: looking at lets say -5, we see 1011. We ignore the sign bit (1)011 and reverse the other bits: 011 becomes 100 ... now look up 100 and we see that = 4. To this we add the 1. and we get 5. To this we add the minus bit and end up with -5 ... simple stuff Anytime you do math and the number of bits exceed the number of bits available to store the number, you get an overflow condition. With unsigned math (using the above 4 bit values) you can see that adding 1 to 15 or 0001 + 1111 is going to result in 16 or 10000 (hmm, wheres that extra bit go? we overflowed into the value sitting beside us in memory. whoops!) With signed math (using the above 4 bit values) you can see that adding 1 to 7 or 0001 + 0111 is going to result in -8 or 1000 (hmm, whoops, we just broke something) Detecting unsigned overflow is a lot easier then signed overflow as it corrupts the value in the next location. Signed overflow does not corrupt anything, it just converts the number into something unexpected. Now, in our particular bug ... we are using much larger numbers, but the rules are the same ... 0111 1111 1111 1111 (32767) + 0000 0000 0000 0001 (1) = 1000 0000 0000 0000 (-32768)
< Message edited by Mr.Frag -- 11/1/2004 8:49:59 AM >
|