在C ++中将64位值左移64位可得到奇怪的结果 [英] Shifting 64 bit value left by 64 bits in C++ giving weird results

查看:548
本文介绍了在C ++中将64位值左移64位可得到奇怪的结果的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


可能重复:

64位移问题

我在Windows 8 64上使用Visual Studio 2012位,使用AMD Phenom II在调试模式下定位x64。

所以基本上...

I'm using Visual Studio 2012 on Windows 8 64-bit, targeting x64 in debug mode, using an AMD Phenom II.
So Basically...

uint64_t Foo = 0xFFFFFFFFFFFFFFFF << 64;//Foo is now 0x0000000000000000
uint64_t Derp = 64;
uint64_t Bar = 0xFFFFFFFFFFFFFFFF << Derp;//Foo is now 0xFFFFFFFFFFFFFFFF

使用较低的值(例如63)可以恢复正常行为。

为什么会发生这种情况,如何解决呢?

Using a lower value such as 63 restores normal behavior.
Why is this happening and how can I get around it?

更新:我切换到发布模式。瞧,问题消失了,并且都返回了0。但是问题仍然处于调试模式,这是调试我的代码所需要的方式。

Update: I switched to release mode. Lo and behold, the issue vanished and both returned 0. But the issue remains in debug mode which is where I need to be in order to debug my code.

推荐答案

如果按大于或等于位宽的值进行移位,则移位操作具有不确定的行为。

Shift operation has undefined behavior if you shift by values greater than or equal to the bit width.

来自C +中的5.8 p1节+11草稿:

From Section 5.8 p1 in the C++11 draft:


操作数应为整数或无范围枚举类型,并执行整数提升。
结果的类型是提升后的左操作数的类型。如果右操作数
为负,或者大于或等于提升后的左操作数的位长度,则该行为是不确定的。

The operands shall be of integral or unscoped enumeration type and integral promotions are performed. The type of the result is that of the promoted left operand. The behavior is undefined if the right operand is negative, or greater than or equal to the length in bits of the promoted left operand.

这篇关于在C ++中将64位值左移64位可得到奇怪的结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆