Please let me know if there's any other way I can do it I heard that there is an overflow flag in the hardware I've never seen it on C/C++.
int a, b, c;
test=a*b;
if (test/b!=a) {} //overflow detection -> proper handling
else c=test; // No overflow
The left-most-bit allows you to detect overflows in advance.
In addition, all top-level bits of the operand are less than 32 and do not overflow.
bool addition_is_safe(uint32_t a, uint32_t b) {
size_t a_bits=leftMostBit(a), b_bits=leftMostBit(b);
return (a_bits<32 && b_bits<32);
}
Multiplication does not overflow if the value of the operator's top bit is less than 32
bool multiplication_is_safe(uint32_t a, uint32_t b) {
size_t a_bits=leftMostBit(a), b_bits=leftMostBit(b);
return (a_bits+b_bits<=32);
}
This is not a perfect method. In addition to a+b, even if a's left-most-bit is 32, if b is 0, it doesn't actually overflow.
But I think there's some sense in the sense of overflow detection.
© 2024 OneMinuteCode. All rights reserved.