You can detect overflow in advance by dividing the maximum value representable by the unsigned type by one of the multiplicands; if the result is less than the other multiplicand, then multiplying them would result in a value exceeding the range of the unsigned type.
For example, in C++ (using the C++0x exact-width numeric types):
std::uint64_t left = 12;
std::uint64_t right = 42;
if (left != 0 && (std::numeric_limits<std::uint64_t>::max() / left) < right)
{
// multiplication would exceed range of unsigned
}
In C, you can use uint64_t
for the type and UINT64_MAX
for the maximum value. Or, if you only care that the type is at least 64 bits wide and not necessarily exactly 64 bits wide, you can use unsigned long long
and ULLONG_MAX
.