问题描述
我有一个 __int64 变量 x = 0x8000000000000000
.
I have a __int64 variable x = 0x8000000000000000
.
我尝试按字节右移:x >>4
我认为结果应该是0x0800000000000000
,但不幸的是我得到了0xf800000000000000
.
I`ve thought that the result should be 0x0800000000000000
, but unfortunately I get 0xf800000000000000
.
我使用 VS10.为什么会这样?我该如何解决?
I use VS10. Why is it so? And how can I solve that?
推荐答案
原因是因为只有左操作数至少为 0 时,才由语言定义移动有符号数.在您的情况下,我假设它是二进制补码表示并且您的数字是负数,因此未指定结果(或实现定义,我现在手头没有参考资料).通常,您会得到逻辑移位或算术移位.
The reason is because shifting signed numbers is only defined by the language if the left operand is at least 0. In your case I assume it's a twos-complement representation and your number is negative making the result unspecified (or implementation-defined, I don't have the reference at hand right now). Typically you would either get a logical shift or an arithmetic shift.
如果您可以将变量设为无符号就可以解决您的问题.
If you can get away with making your variable unsigned that would solve your problem.
这篇关于用 64 位 int 移位的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!