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

问题描述

可能的重复:
64 位移位问题

我在 Windows 8 64 位上使用 Visual Studio 2012,在调试模式下针对 x64,使用 AMD Phenom II.
所以基本上...

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++11 草案中的第 5.8 p1 节:

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

操作数应为整数或无作用域枚举类型,并执行整数提升.结果的类型是提升的左操作数的类型.如果正确的操作数,则行为未定义为负,或大于或等于提升的左操作数的位长度.

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

07-16 16:11
查看更多