-
Notifications
You must be signed in to change notification settings - Fork 1
2.2 operating integers
Perform safe and portable integer operations.
To convert between integer types, use boost::numeric_cast
:
using boost::numeric_cast;
int i = numeric_cast<int>(i); // where i may be an unsigned int
To handle operations which result in overflows, you can either use a freely available package called "SafeInt", or try to perform operations on an unsigned integer type with a same length.
Narrowing conversions and overflows are not a problem until you fully understand the situation. For short, overflow is merely a "gentle" name of an undefined behavior when a result does not fit in a representation, where whether a representation uses 2's complement is implementation-defined. In a word, try not to reply on them.
Overflows only applies to operations result in a signed integer
type, and can be addressed by boost::positive_overflow
and
boost::negative_overflow
when you convert an unsigned integer
into a signed integer.
Boost.NumericConversion: http://www.boost.org/libs/numeric/conversion/