| Home | Libraries | People | FAQ | More

## Compile Time log2 Calculation

The class template in <boost/integer/static_log2.hpp> determines the position of the highest bit in a given value. This facility is useful for solving generic programming problems.

### Synopsis

    namespace boost
    {

      typedef implementation-defined static_log2_argument_type;
      typedef implementation-defined static_log2_result_type;

      template <static_log2_argument_type arg>
      struct static_log2
      {
        static const static_log2_result_type value = implementation-defined;
      };

      template < >
      struct static_log2< 0 >
      {
        // The logarithm of zero is undefined.
      };

    }  // namespace boost

### Usage

The `boost::static_log2` class template takes one template parameter, a value of type `static_log2_argument_type`. The template only defines one member, `value`, which gives the truncated, base-two logarithm of the template argument.

Since the logarithm of zero, for any base, is undefined, there is a specialization of `static_log2` for a template argument of zero. This specialization has no members, so an attempt to use the base-two logarithm of zero results in a compile-time error.

Note:

- `static_log2_argument_type` is an unsigned integer type (C++ standard, 3.9.1p3).
- `static_log2_result_type` is an integer type (C++ standard, 3.9.1p7).

### Demonstration Program

The program static_log2_test.cpp is a simplistic demonstration of the results from instantiating various examples of the binary logarithm class template.

### Rationale

The base-two (binary) logarithm, abbreviated lb, function is occasionally used to give order-estimates of computer algorithms. The truncated logarithm can be considered the highest power-of-two in a value, which corresponds to the value's highest set bit (for binary integers). Sometimes the highest-bit position could be used in generic programming, which requires the position to be available statically (i.e. at compile-time).

### Credits

The original version of the Boost binary logarithm class template was written by Daryle Walker and then enhanced by Giovanni Bajo with support for compilers without partial template specialization. The current version was suggested, together with a reference implementation, by Vesa Karvonen. Gennaro Prota wrote the actual source file.