Shifting 64 bit value left by 64 bits in C++ giving weird results [duplicate]

那年仲夏 提交于 2020-05-07 19:28:23

问题


Possible Duplicate:
64bit shift problem

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

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

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.


回答1:


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

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.




回答2:


I believe shifting by the size of the integer or larger is undefined in C++.

Your first example is being evaluated at compile time as it involves only constants. Your second example is computed at run-time by the processor.

You can split the shift into two parts:

uint64_t Bar = 0xFFFFFFFFFFFFFFFF << (Derp / 2);
Bar <<= Derp - (Derp / 2);


来源:https://stackoverflow.com/questions/11817391/shifting-64-bit-value-left-by-64-bits-in-c-giving-weird-results

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!