如何在uint64_t中移位> = 32位?

Fra*_*ank 3 c++ bit-manipulation

以下代码触发gcc警告(gcc 4.2.1):

#include <boost/cstdint.hpp>
boost::uint64_t x = 1 << 32; // warning: left shift count >= width of type
Run Code Online (Sandbox Code Playgroud)

不应该没问题,因为该类型有64位?

Rob*_*obᵩ 11

如何移位> = 32位uint64_t

如果您的编译器支持long long:

boost::uint64_t x = 1LL << 32;
Run Code Online (Sandbox Code Playgroud)

除此以外:

boost::uint64_t x = boost::uint64_t(1) << 32;
Run Code Online (Sandbox Code Playgroud)

不应该没问题,因为该类型有64位?

不.虽然x是64位,但1不是.1是32位.如何使用结果不会影响结果的生成方式.

  • 或者:`uint64_t x = 1; x << = 32;` (5认同)
  • 这是对C++中类型如何工作的常见误解.如何*使用*结果对结果的生成方式没有影响.`1 << 32`是`1 << 32`.如果你有`int foo(int);`和`double foo(double);`,如果你执行`double bar = foo(1);`,你将结果存储在double中的事实不影响哪个`foo`被召唤. (4认同)