The Boost Integer Library

The Boost Integer library resolves some of the tricky problems in portably using integer typed variables in C++. These problems arise from the multiple uses of integer types for both mathematical calculations and indexing and accessing memory and are generally present in other low-level programming languages too. The library also provides tools for generic programing with integer types.

The simplest fragment of using the library in practice is:

// Declare an integer variable that is at least 16-bits wide but is
// wider at the discretion of the compiler if that will generally
// produce faster code
boost::uint_fast16_t i;

The main features of the library are:

  • Providing fixed-with integer types such as ''boost::int8_t'', ''boost::uint8_t'', ''boost::int16_t'', etc., that always have the same range on any platform and C++ implementation
  • Providing integer types with at least a certain width: ''boost::int_least8_t'', ''boost::int_fast8_t'', etc.
  • Template classes for selection of correct integer types in generic programming

The main problem this library is designed to solve is that the traditional C++ integer types such as int, long int, etc, have widths which depend on the combination of the platform and compiler used. Therefore if you need to write portable programs that depend on a particular range of integer types, you need to use the Boost Integer library.

The following simple but complete program illustrates using the integer library to create an integer variable and then check the number of bits that it has:

#include <iostream>
#include <boost/cstdint.hpp>
#include <boost/integer_traits.hpp>

int main(void)
{
  // An unsigned integer that is at least 8bits wide but can be wider
  // for performance reasons
  typedef boost::uint_fast8_t t;
  t a;
  std::cout<<"uint_fast8 is "
           <<boost::integer_traits<t>::digits
           <<" bits wide on 32bit Linux & g++ 4.3"
           <<std::endl;
}