简体   繁体   English

C中的位移位,意外结果

[英]bit shifting in C, unexpected result

when i pass n = 0x0 , i get 0xffffffff on the screen which i expect should be 0x00000000 as i shift the word by 32 bits (Just Ignore the x! I didn't use it inside the function.) 当我通过n = 0x0 ,我在屏幕上得到0xffffffff ,我希望它是0x00000000因为我将字移位了32 bits (请忽略x!我没有在函数内使用它。)

void logicalShift(int x, int n) {
    int y = 32;
    int mask = 0xffffffff;
    printf("mask %x", mask << (y-n));
}

One of the interesting point is 有趣的一点是

void logicalShift(int x, int n) {
    int y = 32;
    int mask = 0xffffffff;
    printf("mask %x", mask << 32);
}

this will output what i expected. 这将输出我所期望的。 Do i miss out anything? 我会错过任何东西吗? Thank you! 谢谢!

Im running on ubuntu 我在Ubuntu上运行

A shift left of 32 bits on a 32 bit value has undefined results. 在32位值上向左移32位会产生不确定的结果。 You can only shift 0 to 31 bits. 您只能将0到31位移位。

See also here: Why doesn't left bit-shift, "<<", for 32-bit integers work as expected when used more than 32 times? 另请参见此处: 为什么使用32次以上的整数时,32位整数的左移位“ <<”不按预期工作?

Here is the relevant quote from the C11 draft §6.5.7.3 ; 这是C11草案§6.5.7.3中的相关报价;

If the value of the right operand is negative or is greater than or equal to the width of the promoted left operand, the behavior is undefined. 如果右操作数的值为负或大于或等于提升后的左操作数的宽度,则行为未定义。

In other words, the result is undefined, and the compiler is free to generate any result. 换句话说,结果是不确定的,编译器可以自由生成任何结果。

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

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