相关疑难解决方法(0)

右移算子的奇怪行为(1 >> 32)

我最近使用右移运算符遇到了一种奇怪的行为.

以下程序:

#include <cstdio>
#include <cstdlib>
#include <iostream>
#include <stdint.h>

int foo(int a, int b)
{
   return a >> b;
}

int bar(uint64_t a, int b)
{
   return a >> b;
}

int main(int argc, char** argv)
{
    std::cout << "foo(1, 32): " << foo(1, 32) << std::endl;
    std::cout << "bar(1, 32): " << bar(1, 32) << std::endl;
    std::cout << "1 >> 32: " << (1 >> 32) << std::endl; //warning here
    std::cout << "(int)1 >> (int)32: " << ((int)1 …
Run Code Online (Sandbox Code Playgroud)

c c++ bit-manipulation bit-shift

21
推荐指数
2
解决办法
3554
查看次数

为什么`int >> 32`不总是为零?

有人可以解释一下为什么在C/C++中,一些4字节整数的32位按位移位可能不会返回零?为什么它取决于-O编译器的选项?

例如,此代码在gcc 4.8.3中给出45 -O0和0以及-O3选项:

unsigned int x = 45; // 4 bytes
x = x >> 32;
printf("%u\n", x);
Run Code Online (Sandbox Code Playgroud)

为什么会这样?

c c++ bit-manipulation shift

3
推荐指数
1
解决办法
211
查看次数

为什么<< 32在javascript中不会导致0?

这是假的:

(0xffffffff << 31 << 1) === (0xffffffff << 32)
Run Code Online (Sandbox Code Playgroud)

看起来应该是真的.添加>>> 0任何地方都不会改变这一点

为什么这样,我怎样才能正确编写处理的代码<< 32

javascript unsigned bit-manipulation integer-overflow bit-shift

2
推荐指数
1
解决办法
156
查看次数