问题描述
我有点困惑,因为我想初始化一个类型为unsigned long
的变量,该变量在我的系统上(我设想的每个现代系统上)的大小为8个字节.当我想给变量1 << 63
赋值时,我得到一个编译器警告,但是实际上数字是0.当我执行1 << 30
时,我得到了2 ^ 30 = 1073741824
的预期结果.但是,当我执行1 << 31
时,会得到打印18446744071562067968
的2 ^ 64
的结果(我认为;实际上这是不可能的).
I'm a bit confused because I wanted to initialize a variable of type unsigned long
whose size is 8 bytes on my system (on every modern system I suppose). When I want to assign 1 << 63
to the variable, I get a compiler warning however and the number is in fact 0. When I do 1 << 30
I get the expected result of 2 ^ 30 = 1073741824
. Yet when I do 1 << 31
, I get the result of 2 ^ 64
(I think; actually this shouldn't be possible) which prints 18446744071562067968
.
有人可以向我解释这种行为吗?
Can anyone explain this behaviour to me?
推荐答案
1 << 63
将以int
算术方式计算,而您的int
可能为32位.
1 << 63
will be computed in int
arithmetic, and your int
is probably 32 bit.
通过提出以下论点之一来解决此问题:1ULL << 63
会做到这一点.
Remedy this by promoting one of the arguments: 1ULL << 63
will do it.
ULL
表示表达式至少为64位.
ULL
means the expression will be at least 64 bits.
这篇关于使用无符号long类型进行位移位会产生错误的结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!