C : Convert signed to unsigned

你离开我真会死。 提交于 2019-12-04 06:34:20

问题


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


回答1:


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.




回答2:


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


来源:https://stackoverflow.com/questions/3825194/c-convert-signed-to-unsigned

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!