请检查下面的代码,让我知道为什么这没有给出预期的结果。
#include <stdio.h>
int main()
{
unsigned short y=0;
unsigned char x=0xe0; //binary - 1110 0000
unsigned char z=3;
y = (x<< z);
printf("\n y value is %x\n",y);
return 0;
}
我期望 y 应该打印 0x00,但它打印的是 0x0700。你能告诉我左移和赋值操作在这里是如何工作的吗?
谢谢
最佳答案
根据规范,位移运算符的左操作数进行整数提升。
所以:
y = (x<< z);
在这里等同于:
y = ((int) x << z);
<<
的结果expression 是提升后的左操作数的类型,i。即,int
并转换为 unsigned short
在分配期间。
关于C 左移与赋值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26097413/