使用格式说明符%d和%u将类型转换〜0转换为unsigned int和unsigned short,对于short产生相同的结果,但对于int产生不同的结果

问题描述

在计算有符号和无符号的char,short,int和long变量范围时,我采用了以下解决方案:

  1. https://stackoverflow.com/a/19085193/11320006

  2. http://www.learntosolveit.com/cprogramming/Ex_2.1_cal_limits.html

根据解决方案1,我希望下面的代码中的(unsigned short)~0输出-1和65535,假设其行为与两个格式说明符的(unsigned int)~0代码相同。

// the two statements below produce different results
printf("Value of unsigned int is %d\n",(unsigned int)~0); // outputs -1                                                                                                                                                     
printf("Value of unsigned int is %u\n",(unsigned int)~0); // outputs 4294967295

// whereas,the two statements below produce the same result. Why?
printf("Value of short unsigned int is %d\n",(unsigned short)~0); // outputs 65535,expected -1
printf("Value short unsigned int is %u\n",(unsigned short)~0); // outputs 65535

为什么(unsigned short)~0(unsigned int)~0的行为有所不同?

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)