cppx-core
intlog2.hpp
Go to the documentation of this file.
1 #pragma once // Source encoding: UTF-8 with BOM (π is a lowercase Greek "pi").
2 
6 #include <cppx-core/language/syntax/macro-use.hpp> // CPPX_USE_CPPX
7 
8 #include <c/limits.hpp> // INT_MAX
9 #include <c/stdint.hpp> // uint8_t
10 
11 #include <type_traits> // std::is_unsigned_v
12 
13 namespace cppx
14 {
16  namespace impl
17  {
18  constexpr inline auto log2_8( const uint8_t x ) noexcept
19  -> int
20  {
21  constexpr int logs[] =
22  {
23  -1, 0, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3, 3, 3
24  };
25  //static_assert( array_size_of( logs ) == 16 );
26 
27  return (x & 0xF0? 4 + logs[x >> 4] : logs[x]);
28  }
29 
30  constexpr inline auto log2_16( const uint16_t x ) noexcept
31  -> int
32  { return (x & 0xFF00? 8 + log2_8( uint8_t( x >> 8 ) ) : log2_8( uint8_t( x ))); }
33 
34  constexpr inline auto log2_32( const uint32_t x ) noexcept
35  -> int
36  { return (x & 0xFFFF0000? 16 + log2_16( uint16_t( x >> 16 ) ) : log2_16( uint16_t( x ) )); }
37 
38  constexpr inline auto log2_64( const uint64_t x ) noexcept
39  -> int
40  { return (x & 0xFFFFFFFF00000000? 32 + log2_32( uint32_t( x >> 32 ) ) : log2_32( uint32_t( x ))); }
41 
42  constexpr inline auto log2( const uint8_t x ) noexcept -> int { return log2_8( x ); }
43  constexpr inline auto log2( const uint16_t x ) noexcept -> int { return log2_16( x ); }
44  constexpr inline auto log2( const uint32_t x ) noexcept -> int { return log2_32( x ); }
45  constexpr inline auto log2( const uint64_t x ) noexcept -> int { return log2_64( x ); }
46  } // namespace impl
48 
50  //
51  template< class Unsigned >
52  constexpr inline auto intlog2( const Unsigned x ) noexcept
53  -> int
54  {
55  static_assert( std::is_unsigned_v<Unsigned> );
56  return impl::log2( x );
57  }
58 
59  namespace bitlevel
60  {
62  } // namespace bitlevel
63 } // namespace cppx
CPPX_USE_CPPX(bits_per_, magnitude_bits_per_)
constexpr auto intlog2(const Unsigned x) noexcept -> int
The position of the most significant bit in an unsigned value, or -1 for value zero.
Definition: intlog2.hpp:52
Macros for generating more concise and clear using statements, primarily $use_cppx and $use_std,...