c++ - determine if multiplication output fits into max value of 64 bits -
this question has answer here:
- how detect integer overflow? 30 answers
i have multiplication line can result in output greater 64 bit values. (max can hold).
i want determine best way determine if output greater 64 bits.
i have tried things like.
uint64_t val1, val2, val3; if ((val1 * val2 * val3 ) > uint64_max) { //warning message } else { //do } variables initialized values.
a multiplication a * b of 2 unsigned (!) integer numbers of arbitrary size, let's call type t, overflow if , if result greater maximum number t can hold. standard library can access maximum number of type t using std::numeric_limits.
the above statement can written as: a * b overflow if , if a > max(t) / b, same b > max(t) / a (where / integer division , max(t) maximum number t can hold).
example: let's t = uint8_t, max(t) == 255. couple of examples demonstration:
a | 16 | 15 | 14 b | 16 | 17 | 18 --------------------------------- * b | 256 | 255 | 252 overflow? | yes | no | no --------------------------------- max(t)/b | 15 | 15 | 14 > max(t)/b? | yes | no | no use method check if multiplication a * b overflow:
#include <limits.h> template<typename t> bool multiplicationwilloverflow(t a, t b) { return > std::numeric_limits<t>::max() / b; } then, use method twice on product of 3 numbers:
uint64_t val1, val2, val3; if (multiplicationwilloverflow(val1, val2)) { //warning message } uint64_t product12 = val1 * val2, else if (multiplicationwilloverflow(product12, val3)) { //warning message } uint64_t product123 = product12 * val3; another option encapsulate multiplication , check in one method. throw exception if overflow occurs.
template<typename t> t safemultiplication(t a, t b) { if (a > std::numeric_limits<t>::max() / b) throw ...; else return * b; } you can encapsulate behavior in custom type, overloads arithmetic operators , throws if overflow happen.
don't use exceptions if expect overflows "normal behavior" / under "normal circumstances". in such cases, use error parameter / flag in custom type instead.
a similar thing done in floating point arithmetic nan exceptional states: continuing calculation nan value result in nan again. similar implementation flagging overflow in custom type make sure can detect overflow in chained calculations, product of 3 numbers, easily. point custom type don't have write expression calculated twice: calculation plus overflow checking in advance.
Comments
Post a Comment