真是郁闷啊(date<<7)>>12
可能是什么原因给出了与 y>>12
不同的结果其中 y
是date<<7
?。我应该补充一点,后者按我的预期正常工作,但第一个不是。有什么区别?我看不出有什么区别。
#include<stdio.h>
int main()
{
unsigned short date=5225,x,y,z;
x=(date<<7)>>12;
printf("Month is %hu\n",x);
y=date<<7;
z=y>>12;
printf("Month is %hu\n",z);
}
输出
Month is 163
Month is 3
最佳答案
在 C 中,所有整数计算都至少提升到 int
1。所以
x = (date << 7) >> 12
= (5225 << 7 /* result as int */) >> 12
= 668800 >> 12
= 163
计算完成后,我们将结果截断回 unsigned short
以获得 163。
在第二种情况下,y
强制将结果截断为 unsigned short
,因此
y = (unsigned short) (date << 7)
= (unsigned short) 668800
= 13440
z = y >> 12
= 3
1:C11 §6.5.7/3:“对每个操作数执行整数提升。结果的类型是提升后的左操作数的类型。”; §6.3.1.1/2:“如果 int
可以表示原始类型的所有值(受宽度限制,对于位字段),则该值将转换为 int
;否则,它会转换为 unsigned int
。这些称为整数提升。”
关于c - 如果 "x=(date<<7)>>12"和 {y=date<<7;z=y>>12;} 为什么 x 和 z 的评估不同?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16484927/