|
Re: tank drive
Signed math just tells the compiler to interpret the bits differently. Internally the CPU uses something called 2-complement to represent the negative numbers. A number in 2-complement form can be added to another number and you will get the right results without any special hardware. However, you can't generate a 2-complement number by simply flipping the sign bit (bit 8). For example: 0x01 2-complement is 0xFF. 0xFF is 255 in unsigned math.
So, to represent a negative 5 in binary, you would complement 00000101 to get 11111010 then add one to get 11111011
So, add -5 and, say, 7 (in binary):
11111011
00000111
---------
100000010
The 9th bit falls off the end of the earth (or into the "carry" bit) and the resulting number is just 2. When adding larger numbers (int, short long and long) the bytes are added sequentially and the carry from the previous add is added into the first bit of the next.
When converting shorter to longer (e.g. a byte to an int) you simply copy the 8th bit into all bits of the next higher byte and the value is preserved. This is all done for you by the compiler.
|