1 // Boost integer/static_log2.hpp header file -------------------------------//
3 // (C) Copyright Daryle Walker 2001. Permission to copy, use, modify, sell and
4 // distribute this software is granted provided this copyright notice appears
5 // in all copies. This software is provided "as is" without express or
6 // implied warranty, and with no claim as to its suitability for any purpose.
8 // See http://www.boost.org for updates, documentation, and revision history.
10 #ifndef BOOST_INTEGER_STATIC_LOG2_HPP
11 #define BOOST_INTEGER_STATIC_LOG2_HPP
13 #include <boost/integer_fwd.hpp> // self include
15 #include <boost/config.hpp> // for BOOST_STATIC_CONSTANT
16 #include <boost/limits.hpp> // for std::numeric_limits
23 // Implementation details --------------------------------------------------//
28 // Forward declarations
29 template < unsigned long Val, int Place = 0, int Index
30 = std::numeric_limits<unsigned long>::digits >
31 struct static_log2_helper_t;
33 template < unsigned long Val, int Place >
34 struct static_log2_helper_t< Val, Place, 1 >;
36 // Recursively build the logarithm by examining the upper bits
37 template < unsigned long Val, int Place, int Index >
38 struct static_log2_helper_t
41 BOOST_STATIC_CONSTANT( int, half_place = Index / 2 );
42 BOOST_STATIC_CONSTANT( unsigned long, lower_mask = (1ul << half_place)
44 BOOST_STATIC_CONSTANT( unsigned long, upper_mask = ~lower_mask );
45 BOOST_STATIC_CONSTANT( bool, do_shift = (Val & upper_mask) != 0ul );
47 BOOST_STATIC_CONSTANT( unsigned long, new_val = do_shift ? (Val
48 >> half_place) : Val );
49 BOOST_STATIC_CONSTANT( int, new_place = do_shift ? (Place + half_place)
51 BOOST_STATIC_CONSTANT( int, new_index = Index - half_place );
53 typedef static_log2_helper_t<new_val, new_place, new_index> next_step_type;
56 BOOST_STATIC_CONSTANT( int, value = next_step_type::value );
58 }; // boost::detail::static_log2_helper_t
61 template < unsigned long Val, int Place >
62 struct static_log2_helper_t< Val, Place, 1 >
65 BOOST_STATIC_CONSTANT( int, value = Place );
67 }; // boost::detail::static_log2_helper_t
72 // Compile-time log-base-2 evaluator class declaration ---------------------//
74 template < unsigned long Value >
77 BOOST_STATIC_CONSTANT( int, value
78 = detail::static_log2_helper_t<Value>::value );
82 struct static_log2< 0ul >
84 // The logarithm of zero is undefined.
91 #endif // BOOST_INTEGER_STATIC_LOG2_HPP