views:

89

answers:

2

Hi there,

Actually I've (probably) a "simple" problem. So I don't know how to cast a signed integer to an unsigned integer.

My code :

signed int entry = 0;
printf("Decimal Number : ");
scanf("%d", &entry);
unsigned int uEntry= (unsigned int) entry;
printf("Unsigned : %d\n", uEntry);

If I send the unsigned value to the console (see my last code line), I always get back an signed integer.

Can you help me?

Thanks a lot!

Kind regards, pro

+8  A: 
printf("Unsigned : %u\n", uEntry);
//                 ^^

You must use the %u specifier to tell the printf runtime that the uEntry is an unsigned int. If you use %d the printf function will expect an int, thus reinterpret your input back to a signed value.

KennyTM
Hi Kenny, Thanks for your answer. If I set the %u specifier, I will get for -13 an unsigned value of 4294967283. What's the problem. Thanks.
pro
There's no problem. That is the unsigned representation of the bits of your variable.
Juri Robl
@pro: When your format specifier doesn't match the type of the value you are printing, the behavior is undefined and the results are meaningless. I.e. when you print `-13` with `%u` the results are meaningless. As well as your original attempt to print an unsigned value with `%d`. Always use the correct format specifier, if you want your output to make sense: `%u` for `unsigned int`, `%d` for `signed int`.
AndreyT
@pro: -13 is out of range for `unsigned int`. When you convert an out-of-range number to an unsigned type, it is brought into range by repeatedly adding or subtracting one more than the maximum value of the type - in this case, `UINT_MAX + 1`, which is 4294967296 on your platform, is added to -13 to give 4294967283.
caf
Hi guys, thank you for your answers and comments. It was very useful!
pro
+1  A: 

Append these two lines at the end of your code, and you would understand what is going on.

printf("entry: signed = %d, unsigned = %u, hex = 0x%x\n", entry, entry entry);
printf("uEntry: signed = %d, unsigned = %u, hex = 0x%x\n", uEntry,uEntry,uEntry);
ArunSaha
While it may be informative in explaining how your particular implementation works, both of these calls result in undefined behavior. You have to provide the correct types to `printf` according to what you specified in the format string in order for the results to be well-defined.
R..