无符号长长溢出错误? [英] Unsigned long long overflow error?
问题描述
我在使用 unsigned long long 时遇到了一些奇怪的问题.
I have been having some strange issues with unsigned long long.
当我设置一个 unsigned long long 时会发生这种情况(我使用了 size_t,但是这个问题可以用 u-l-l 重复).我已将其设置为 2^31,但由于某种原因,它恢复为 18446744071562067968,或 2^64 - 2^31.请记住,我使用的是 x64 编译:
It happens when I set an unsigned long long (I used size_t, however the problem is repeatable with u-l-l). I have set it to 2^31, however for some reason it reverts to 18446744071562067968, or 2^64 - 2^31. Keep in mind I am using an x64 compilation:
unsigned long long a = 1 << 31;
cout << a;
//Outputs 18446744071562067968, Expected 2147483648
我认为 u-l-l 的限制是 2^64-1?那么为什么不能存储 2^31 呢?2^30 工作得很好.Sizeof(a) 返回 8,如果我没记错的话是 64 位,证明了 2^64-1 的极限.
I thought the limits of u-l-l were 2^64-1? So why can 2^31 not be stored? 2^30 works just fine. Sizeof(a) returns 8, which is 64 bits if I am not mistaken, proving the limit of 2^64-1.
我正在 Visual C++ 2013 Express Desktop 上编译.
I am compiling on Visual C++ 2013 Express Desktop.
我唯一的猜测是它是某种类型的溢出错误,因为它不适合正常的 long 类型.
My only guess is that it is some type of overflow error because it doesn't fit a normal long type.
推荐答案
当负整数值分配给 unsigned long long 时,您看到的是符号扩展.
What you're seeing is sign extension when the negative integer value is assigned to the unsigned long long.
要修复它,您需要先将值设为无符号,如下所示:
To fix it you need to make the value unsigned to begin with, something like this:
#include <iostream>
#include <iomanip>
int main()
{
unsigned long long a = 1ull << 31ull;
std::cout << a << "\n";
std::cout << std::hex << a << "\n";
return 0;
}
如果您将警告级别设置得足够高 (/W4),您会看到有关有符号/无符号不匹配的警告.
If you have the warning level set high enough (/W4) you'd see a warning about the signed/unsigned mismatch.
为了完整起见,您不需要限定两个参数,只需要左操作数就可以了,所以 unsigned long long a = 1u <<31;
会工作.我只是希望尽可能明确.
Just to be complete, you don't need to qualify both arguments, just the left operand is fine, so unsigned long long a = 1u << 31;
would work. I just prefer to be as explicit as possible.
这篇关于无符号长长溢出错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!