user5965026
user5965026

Reputation: 485

Multiplying 2 32 bit ints without integer overflow

I would like to multiple 2 positive signed 32-bit integers i and j. The worst case scenario is when i and j are both INT_MAX where their product is within the limit of a 64-bit integer, but when I perform the operation

int i = INT_MAX;
int j = INT_MAX;
long long int res = i * j;

I get garbage due to integer overflow. So I've typically solved that problem by casting i or j to a long long int

int i = INT_MAX;
int j = INT_MAX;
long long int res = (long long int)i * j;

Is this the typical workaround for this issue? Are there other ways that may be better?

Upvotes: 0

Views: 796

Answers (1)

MSalters
MSalters

Reputation: 179819

Your solution is correct, and standard enough that quality compilers will recognize it. Some CPU's have dedicated 32x32->64 multiplication instructions, and you can reasonably expect a compiler to use such an instruction despite the cast.

Upvotes: 3

Related Questions