Interface Documentation
Version: invalid
bitutils.hh
Go to the documentation of this file.
1 /*
2  @@@@@@@@ @@ @@@@@@ @@@@@@@@ @@
3  /@@///// /@@ @@////@@ @@////// /@@
4  /@@ /@@ @@@@@ @@ // /@@ /@@
5  /@@@@@@@ /@@ @@///@@/@@ /@@@@@@@@@/@@
6  /@@//// /@@/@@@@@@@/@@ ////////@@/@@
7  /@@ /@@/@@//// //@@ @@ /@@/@@
8  /@@ @@@//@@@@@@ //@@@@@@ @@@@@@@@ /@@
9  // /// ////// ////// //////// //
10 
11  Copyright (c) 2016, Triad National Security, LLC
12  All rights reserved.
13  */
14 #pragma once
15 
18 #include <cstddef>
19 #include <limits>
20 #include <type_traits>
21 
22 namespace flecsi {
23 namespace util {
24 
26 template<class T>
27 constexpr T
28 bit_width(T x) noexcept {
29  static_assert(std::is_unsigned_v<T>);
30  T ret = 0, d = std::numeric_limits<T>::digits;
31  const auto high = [&] { return x >= T(1) << d - 1; };
32  if(high())
33  return d; // avoid overwide >>= below
34  // Perform a binary search for the first 1. The static number of iterations
35  // makes this significantly faster (at runtime) than a traditional search.
36  while(d >>= 1)
37  if(high()) {
38  x >>= d;
39  ret += d;
40  }
41  return ret;
42 }
43 
44 } // namespace util
45 } // namespace flecsi
constexpr T bit_width(T x) noexcept
Simple emulation of std::bit_width from C++20.
Definition: bitutils.hh:28
Definition: control.hh:31