Reputation: 6206
I have implemented the following function for detecting whether or not a multiplication overflows:
bool IsSafeMul(uint32_t x, uint32_t y) {
uint32_t z = x * y;
return (z >= x && z >= y);
}
I have verified it empirically, but would like to ensure that:
unsigned
type?Upvotes: 1
Views: 116
Reputation: 320747
No, it is not guaranteed to work correctly. For example,
0x000FFFFF * 0x000FFFFF = 0xFFFFE00001
It produces 0xFFE00001
after truncation to 32 bits, which passes your test. But multiplication overflows.
To test for overflow on multiplication you can simply check z / x == y
provided x
is not zero.
Upvotes: 1