|
Re: Signed and unsigned variables
My first attempt at this post did not address the problem ... so second attempt.
The only thing you need to be careful of is that casting is not a shift as it might seem intuitive to be. An unsigned char 0 is not equivalent to a signed char 128. Negative numbers are stored in 2s compliment form. Which means the binary for -1 is:
111111111 11111111
NOT: 10000000 0000000, which might seem to make more sense at first.
They use 2s compliment because it makes all of the standard binary operations work for negative numbers.
If you cast a signed int -1 to an unsigned int, you will get 65,535. When you cast from unsigned to signed it does not touch the binary of the variable, just how its interpreted. Just like how you can print the signed interpretation of an unsigned variable using %d in printf instead of %u.
The best way to understand whats happening when u cast unsigned to signed you really need to look up information on 2s compliment.
If you HAD to perform a shift, you would need to do it manually. Ex:
shiftedUnsignedVar = (unsigned int)(signedVar + 32768); or
shiftedSignedVar = (int)(unsignedVar - 32768);
As showed in fosters output that will match the example that you gave to start with.
Hope that helped,
Ken
Last edited by colt527 : 05-01-2008 at 23:14.
Reason: Added example
|