ilog2.hpp 1.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. // boost heap: integer log2
  2. //
  3. // Copyright (C) 2010 Tim Blechmann
  4. //
  5. // Distributed under the Boost Software License, Version 1.0. (See
  6. // accompanying file LICENSE_1_0.txt or copy at
  7. // http://www.boost.org/LICENSE_1_0.txt)
  8. #ifndef BOOST_HEAP_DETAIL_ILOG2_HPP
  9. #define BOOST_HEAP_DETAIL_ILOG2_HPP
  10. namespace boost { namespace heap {
  11. namespace detail {
  12. template < typename IntType >
  13. struct log2
  14. {
  15. IntType operator()( IntType value )
  16. {
  17. IntType l = 0;
  18. while ( ( value >> l ) > 1 )
  19. ++l;
  20. return l;
  21. }
  22. };
  23. #ifdef __GNUC__
  24. template <>
  25. struct log2< unsigned int >
  26. {
  27. unsigned int operator()( unsigned int value )
  28. {
  29. return sizeof( unsigned int ) * 8 - __builtin_clz( value - 1 );
  30. }
  31. };
  32. template <>
  33. struct log2< unsigned long >
  34. {
  35. unsigned long operator()( unsigned long value )
  36. {
  37. return sizeof( unsigned long ) * 8 - __builtin_clzl( value - 1 );
  38. }
  39. };
  40. #endif
  41. } /* namespace detail */
  42. template < typename IntType >
  43. IntType log2( IntType value )
  44. {
  45. detail::log2< IntType > fn;
  46. return fn( value );
  47. }
  48. }} // namespace boost::heap
  49. #endif /* BOOST_HEAP_DETAIL_ILOG2_HPP */