Log in

View Full Version : Signed and unsigned variables


dmlawrence
05-01-2008, 22:23
What is the proper method to cast from an unsigned to a signed variable?

For example, suppose that u is an unsigned int and i is a signed int.

When u is 0, i should be -32768.
When u is 32768, i should be 0.
When u is 65535, i should be 32767.

Which of the following is correct:
i = (unsigned int) u or
i = (unsigned int) (u - 32768)?

Thanks,
David

mluckham
05-01-2008, 22:34
When u is 0, i should be -32768.
When u is 32768, i should be 0.
When u is 65535, i should be 32767.

Which of the following is correct:
i = (unsigned int) u or
i = (unsigned int) (u - 32768)?


As a matter of form, neither is correct, although the second is closest to your requirements. Assuming you have defined 'u' as unsigned int, and 'i' as int, you use:

i = (int) (u - 32768);

dmlawrence
05-01-2008, 22:40
Thanks!

-David

Foster
05-01-2008, 22:42
int main(int argc, char *argv[])
{
unsigned int u;
int i;

u = 0; // i should be -32768.
i = (unsigned int) u;
printf("%d %u\n",i , u);
i = (unsigned int) (u - 32768);
printf("%d %u\n",i , u);

u = 32768; // i should be 0.
i = (unsigned int) u;
printf("%d %u\n",i , u);
i = (unsigned int) (u - 32768);
printf("%d %u\n",i , u);

u=65535; // i should be 32767.
i = (unsigned int) u;
printf("%d %u\n",i , u);
i = (unsigned int) (u - 32768);
printf("%d %u\n",i , u);
return 0;
}

0 0
-32768 0

32768 32768
0 32768

65535 65535
32767 65535

Your test case with output. Did that help?

colt527
05-01-2008, 23:03
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