ilog2.hpp 1.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  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. #include <string> // std::size_t
  11. namespace boost {
  12. namespace heap {
  13. namespace detail {
  14. template <typename IntType>
  15. struct log2
  16. {
  17. IntType operator()(IntType value)
  18. {
  19. IntType l = 0;
  20. while( (value >> l) > 1 )
  21. ++l;
  22. return l;
  23. }
  24. };
  25. #ifdef __GNUC__
  26. template<>
  27. struct log2<unsigned int>
  28. {
  29. unsigned int operator()(unsigned int value)
  30. {
  31. return sizeof(unsigned int)*8 - __builtin_clz(value - 1);
  32. }
  33. };
  34. template<>
  35. struct log2<unsigned long>
  36. {
  37. unsigned long operator()(unsigned long value)
  38. {
  39. return sizeof(unsigned long)*8 - __builtin_clzl(value - 1);
  40. }
  41. };
  42. #endif
  43. } /* namespace detail */
  44. template <typename IntType>
  45. IntType log2(IntType value)
  46. {
  47. detail::log2<IntType> fn;
  48. return fn(value);
  49. }
  50. } /* namespace heap */
  51. } /* namespace boost */
  52. #endif /* BOOST_HEAP_DETAIL_ILOG2_HPP */