bitsmuggler
bitsmuggler

Reputation: 1729

C : Convert signed to unsigned

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

Upvotes: 1

Views: 4401

Answers (2)

Arun
Arun

Reputation: 20383

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);

Upvotes: 1

kennytm
kennytm

Reputation: 523174

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.

Upvotes: 10

Related Questions