当我尝试左移 32 次时,我发现了一些连线问题。测试函数中的代码应该打印 0x0 的相同结果,但我得到的是“ffffffff,0”。任何人都可以提示代码有什么问题?谢谢!
int test(int n) {
int mask = ~0 << (32 + ~n + 1);
int mask1 = ~0 << (32 + ~0 + 1);
printf("%x, %x\n", mask, mask1);
return mask;
}
int main(){
test(0);
}
最佳答案
在 C 中,移动大小大于类型大小(在您的情况下为 int
)是未定义的行为
从这里topic : 相关引用自 ISO C99 (6.5.7/4)
The result of E1 << E2 is E1 left-shifted E2 bit positions; vacated bits are filled with zeros. If E1 has an unsigned type, the value of the result is E1 × 2E2, reduced modulo one more than the maximum value representable in the result type. If E1 has a signed type and nonnegative value, and E1 × 2E2 is representable in the result type, then that is the resulting value; otherwise, the behavior is undefined.
关于c - 按位左移意外结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16423949/