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

Posted

技术标签:

【中文标题】如何在 uint64_t 中移动 >= 32 位?【英文标题】:How to shift >= 32 bits in uint64_t? 【发布时间】:2013-02-13 04:48:58 【问题描述】:

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

#include <boost/cstdint.hpp>
boost::uint64_t x = 1 << 32; // warning: left shift count >= width of type

类型有64位不应该没问题吧?

【问题讨论】:

【参考方案1】:

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

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

boost::uint64_t x = 1LL << 32;

否则:

boost::uint64_t x = boost::uint64_t(1) << 32;

类型有64位不应该没问题吧?

没有。即使 x 是 64 位,1 也不是。 1 是 32 位。使用结果的方式不会影响结果的生成方式。

【讨论】:

这是对 C++ 中类型如何工作的常见误解。您使用结果的方式对该结果的生成方式没有影响。 1 &lt;&lt; 321 &lt;&lt; 32。如果您有int foo(int);double foo(double);,如果您有double bar = foo(1);,则将结果存储在double 中这一事实不会影响调用哪个foo 或:uint64_t x = 1; x &lt;&lt;= 32;

以上是关于如何在 uint64_t 中移动 >= 32 位?的主要内容,如果未能解决你的问题,请参考以下文章