简体   繁体   English

如果“x =(date << 7)>> 12”和{y = date << 7; z = y >> 12;},为什么x和z的评估方式不同?

[英]Why are x and z evaluating differently if “x=(date<<7)>>12” and {y=date<<7;z=y>>12;}?

It is really frustrating.What is the possible reason that (date<<7)>>12 is giving a different result from y>>12 where y is date<<7 ?.I should add that the latter is working correctly as I intend,but the first is not.What's the difference?I can see none. 这真是令人沮丧。可能的原因是(date<<7)>>12给出了与y>>12不同的结果,其中ydate<<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);

}

OUTPUT OUTPUT

Month is 163

Month is 3

In C, all integer computations are promoted to at least int 1 . 在C语言中,所有整数计算至少提升为int 1 So 所以

x = (date << 7) >> 12
  = (5225 << 7 /* result as int */) >> 12
  = 668800 >> 12
  = 163

after the computation is complete, we truncate the result back to an unsigned short to get 163. 计算完成后,我们将结果截断回unsigned short以获得163。

In the second case, the y forced the result to be truncated to be an unsigned short , so 在第二种情况下, y强制将结果截断为unsigned short ,因此

y = (unsigned short) (date << 7)
  = (unsigned short) 668800
  = 13440
z = y >> 12
  = 3

1 : C11 §6.5.7/3: "The integer promotions are performed on each of the operands. The type of the result is that of the promoted left operand."; 1 :C11§6.5.7/ 3:“整数提升是对每个操作数执行的。结果的类型是提升后的左操作数的类型。” §6.3.1.1/2: "If an int can represent all values of the original type (as restricted by the width, for a bit-field), the value is converted to an int ; otherwise, it is converted to an unsigned int . These are called the integer promotions ." §6.3.1.1/ 2:“如果int可以表示原始类型的所有值(由宽度限制,对于位域),则该值将转换为int ;否则,它将转换为unsigned int这些被称为整数促销 。“

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM