使用无符号long类型进行位移位会产生错误的结果

使用无符号long类型进行位移位会产生错误的结果

本文介绍了使用无符号long类型进行位移位会产生错误的结果的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有点困惑,因为我想初始化一个类型为unsigned long的变量,该变量在我的系统上(我设想的每个现代系统上)的大小为8个字节.当我想给变量1 << 63赋值时,我得到一个编译器警告,但是实际上数字是0.当我执行1 << 30时,我得到了2 ^ 30 = 1073741824的预期结果.但是,当我执行1 << 31时,会得到打印184467440715620679682 ^ 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类型进行位移位会产生错误的结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-30 15:37