Skip to content

2.2 operating integers

Zhihao Yuan edited this page May 15, 2013 · 2 revisions

Problem

Perform safe and portable integer operations.

Solution

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.

Discussion

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.

See also

Boost.NumericConversion: http://www.boost.org/libs/numeric/conversion/

Clone this wiki locally