Adam
Adam

Reputation: 10016

Issues with unsigned long long

I was experimenting with the limits of an unsigned long long in C++ and ran into a bit of trouble. When I multiply 5 million by 5 million like this:

unsigned long long test = 5000000*5000000;

the variable test holds value 18446744072704921600 instead of 25000000000000. My understanding is that unsigned long long can represent 0 to 18446744073709551615, so what is going on here? Thanks!

Upvotes: 4

Views: 1910

Answers (3)

pcodex
pcodex

Reputation: 1940

you can also try

unsigned long long op1 = 5000000;
unsigned long long test = op1 * 5000000;

Upvotes: 0

Jonathan Potter
Jonathan Potter

Reputation: 37132

By default your compiler treats 5000000 as a 32 bit value. When you multiply the two together, you are still only working with 32 bit values, and so it will overflow. The conversion to 64 bit only occurs when the assignment is made to the left side of the equation.

The solution is to make at least one of the operands 64 bit to start with, e.g.:

unsigned long long test = 5000000i64*5000000;

Then the compiler knows to start with a 64 bit value and no overflow will occur.

Upvotes: 7

templatetypedef
templatetypedef

Reputation: 372784

I think the issue here is that the right-hand side is doing the multiplication assuming the operands are ints, so you're getting an overflow. Try changing it to

unsigned long long test = 5000000ULL * 5000000ULL;

and see if that fixes anything.

Hope this helps!

Upvotes: 3

Related Questions