Message ID | 20250606164156.1442682-6-barnabas.pocze@ideasonboard.com |
---|---|
State | New |
Headers | show |
Series |
|
Related | show |
On Fri, Jun 06, 2025 at 06:41:38PM +0200, Barnabás Pőcze wrote: > `has_single_bit()` checks if the given unsigned integer has a single > bit set, that is, whether the number is a power of two or not. > > Not all requirements of the C++20 standard are implemented. > > See https://en.cppreference.com/w/cpp/numeric/has_single_bit > > Signed-off-by: Barnabás Pőcze <barnabas.pocze@ideasonboard.com> > --- > include/libcamera/base/details/cxx20.h | 10 ++++++++++ > 1 file changed, 10 insertions(+) > > diff --git a/include/libcamera/base/details/cxx20.h b/include/libcamera/base/details/cxx20.h > index 2d26db53e..8bf45ff11 100644 > --- a/include/libcamera/base/details/cxx20.h > +++ b/include/libcamera/base/details/cxx20.h > @@ -7,9 +7,19 @@ > > #pragma once > > +#include <type_traits> > + > namespace libcamera::details::cxx20 { > > template<typename T> struct type_identity { using type = T; }; > template<typename T> using type_identity_t = typename type_identity<T>::type; > > +template<typename T> > +constexpr bool has_single_bit(T x) noexcept > +{ > + static_assert(std::is_unsigned_v<T>); > + > + return x != 0 && (x & (x - 1)) == 0; Or, as suggested by cppreference return x && !(x & (x - 1)); > +} > + > } /* namespace libcamera::details::cxx20 */ > -- > 2.49.0 >
diff --git a/include/libcamera/base/details/cxx20.h b/include/libcamera/base/details/cxx20.h index 2d26db53e..8bf45ff11 100644 --- a/include/libcamera/base/details/cxx20.h +++ b/include/libcamera/base/details/cxx20.h @@ -7,9 +7,19 @@ #pragma once +#include <type_traits> + namespace libcamera::details::cxx20 { template<typename T> struct type_identity { using type = T; }; template<typename T> using type_identity_t = typename type_identity<T>::type; +template<typename T> +constexpr bool has_single_bit(T x) noexcept +{ + static_assert(std::is_unsigned_v<T>); + + return x != 0 && (x & (x - 1)) == 0; +} + } /* namespace libcamera::details::cxx20 */
`has_single_bit()` checks if the given unsigned integer has a single bit set, that is, whether the number is a power of two or not. Not all requirements of the C++20 standard are implemented. See https://en.cppreference.com/w/cpp/numeric/has_single_bit Signed-off-by: Barnabás Pőcze <barnabas.pocze@ideasonboard.com> --- include/libcamera/base/details/cxx20.h | 10 ++++++++++ 1 file changed, 10 insertions(+)