Problems with unsigned long long

I experimented with the limits of unsigned long long in C ++ and ran into little problems. When I multiply 5 million by 5 million like this:

unsigned long long test = 5000000*5000000;

      

the variable test

has the value 18446744072704921600 instead of 25000000000000. My understanding is that unsigned long long can represent 0 to 18446744073709551615, so what's going on here? Thank!

+3


source to share


2 answers


By default, your compiler treats 5,000,000 as a 32-bit value. When you multiply two together, you are still only dealing with 32-bit values, and therefore it will overflow. The conversion to 64 bits only happens when the assignment is done on the left side of the equation.

The solution is to run at least one of the 64-bit operands, for example:



unsigned long long test = 5000000i64*5000000;

      

Then the compiler knows to start with a 64-bit value and no overflow occurs.

+6


source


I think the problem here is that the right-hand side is doing the multiplication, assuming the operands are int

s, which is why you get an overflow. Try changing it to

unsigned long long test = 5000000ULL * 5000000ULL;

      



and see what it fixes.

Hope this helps!

+2


source







All Articles