Jonas
Jonas

Reputation: 1069

unsigned long long arithmetics

I'd like to multiply two unsigned integers but I want the result to be in an unsigned long long variable

unsigned long long M;
unsigned int X;
unsigned int Y;

X = 999999;
Y = 9990;
M = X * Y;

M should be 9989990010 but for some reason it keeps being 1400055418

I've been troubled with this for a week now, and I think I reached the point where I want to cry!

Upvotes: 0

Views: 3423

Answers (3)

Collin
Collin

Reputation: 12287

Both X and Y are only ints, so the type of the expression X*Y is an int. The number is converted to long long after the multiply is already done. Make X and Y long longs and you'll get the expected result.

Upvotes: 3

Diego Sevilla
Diego Sevilla

Reputation: 29021

Cast at least one of them to unsigned long long. The other will be cast (promoted) automatically. The problem here is: How do the compiler knows if you want the truncated result of multiplying int values or the result of not truncating, long long value?

Upvotes: 1

littleadv
littleadv

Reputation: 20272

You need to cast the X and Y to long long.

M = (unsigned long long)X * Y;

Enough to cast one of them the result will be based on the larger type.

Otherwise the result will be int, hence the overflow. It will be casted to long long on assignment, but that would be too late:-)

Upvotes: 6

Related Questions