c - 按位左移意外结果

标签 c bit-manipulation bit

当我尝试左移 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/

相关文章:

正确清理信号处理函数

objective-c - 为什么这个 uint32_t 在内存中是这样排序的?

c - 自动换行贪心法

algorithm - 枚举位向量使得不会同时设置两个相邻位的有效方法

c++ - 如何在ascii值超过127的字符串中找到8位子字符串?

c++ - 你为什么不能移动 uint16_t

C 在内存中写入位

python - 如何理解位数组中哪些位设置为 1

c++ - zlib 的压缩函数没有做任何事情。为什么?

c# - 当我传入 64 字节时,为什么 C# Convert.ToBase64String() 给我的长度是 88?