View Single Post
  #5   Spotlight this post!  
Unread 05-01-2008, 23:03
colt527 colt527 is offline
Registered User
AKA: Ken Colton
FRC #0527
Team Role: Mentor
 
Join Date: Feb 2004
Rookie Year: 2002
Location: Long Island
Posts: 123
colt527 is a splendid one to beholdcolt527 is a splendid one to beholdcolt527 is a splendid one to beholdcolt527 is a splendid one to beholdcolt527 is a splendid one to beholdcolt527 is a splendid one to beholdcolt527 is a splendid one to behold
Send a message via AIM to colt527
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
__________________
Mentor, Team 527 -- Plainedge Red Dragons
FIRST Volunteer
SUNY Stony Brook Computer Science 2010
kcolton@gmail.com

Last edited by colt527 : 05-01-2008 at 23:14. Reason: Added example