Unsigned long long overflow error?

Dude Dude

I have been having some strange issues with unsigned long long.

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

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.

I am compiling on Visual C++ 2013 Express Desktop.

My only guess is that it is some type of overflow error because it doesn't fit a normal long type.

Retired Ninja

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;
}

If you have the warning level set high enough (/W4) you'd see a warning about the signed/unsigned mismatch.

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.

本文收集自互联网,转载请注明来源。

如有侵权,请联系[email protected] 删除。

编辑于
0

我来说两句

0条评论
登录后参与评论

相关文章

来自分类Dev

unsigned long long的问题

来自分类Dev

long long转换为unsigned long的问题

来自分类Dev

从unsigned long long转换为unsigned int

来自分类Dev

C unsigned long long和imulq

来自分类Dev

检查unsigned long long是否可用

来自分类Dev

Unsigned long long溢出错误?

来自分类Dev

奇怪的unsigned long long int行为

来自分类Dev

`unsigned long long`太小,无法代表数字?

来自分类Dev

Printf Unsigned Long 的奇怪输出

来自分类Dev

将unsigned long long int强制转换为signed long long int可能吗?

来自分类常见问题

unsigned long long(10)无法在clang和gcc上编译

来自分类Dev

是否可以保证std :: streampos是unsigned long long?

来自分类Dev

如何将unsigned long long转换为double

来自分类Dev

Java相当于unsigned long long不是BigInteger吗?

来自分类Dev

为什么double可以存储比unsigned long long更大的数字?

来自分类Dev

c ++ usigned long long range vs mysql unsigned bigint range

来自分类Dev

unsigned long long(10)无法在clang和gcc上编译

来自分类Dev

将unsigned long long转换为float并失去精度

来自分类Dev

在C ++中将字符串转换为unsigned long long

来自分类Dev

无法将boost :: lambda :: ...转换为long long unsigned int

来自分类Dev

整数类型大于unsigned long long,还有库吗?

来自分类Dev

如何初始化C语言中的unsigned long long

来自分类Dev

在VC6中构建,需要unsigned long long

来自分类Dev

c ++ usigned long long range vs mysql unsigned bigint range

来自分类Dev

带有多个操作数的 unsigned long long 加法

来自分类Dev

在条件断点中使用unsigned long

来自分类Dev

What is the equivalent of unsigned long int in c#?

来自分类Dev

在条件断点中使用unsigned long

来自分类Dev

unsigned long 大于 0xFFFFFFFF

Related 相关文章

热门标签

归档