tetl 0.1.0
Embedded Template Library
Loading...
Searching...
No Matches
popcount.hpp
Go to the documentation of this file.
1// SPDX-License-Identifier: BSL-1.0
2
3#ifndef TETL_BIT_POPCOUNT_HPP
4#define TETL_BIT_POPCOUNT_HPP
5
6#include <etl/_config/all.hpp>
7
12
13namespace etl {
14
15namespace detail {
16
17// https://en.wikichip.org/wiki/population_count
18template <etl::builtin_unsigned_integer UInt>
19[[nodiscard]] constexpr auto popcount_fallback(UInt val) noexcept -> int
20{
21 auto c = 0;
22 for (; val != 0; val &= val - UInt(1)) {
23 c++;
24 }
25 return c;
26}
27
28} // namespace detail
29
37template <etl::builtin_unsigned_integer UInt>
38[[nodiscard]] constexpr auto popcount(UInt val) noexcept -> int
39{
40 if (not is_constant_evaluated()) {
41#if __has_builtin(__builtin_popcount)
42 if constexpr (sizeof(UInt) == sizeof(unsigned long long)) {
43 return static_cast<int>(__builtin_popcountll(val));
44 } else if constexpr (sizeof(UInt) == sizeof(unsigned long)) {
45 return static_cast<int>(__builtin_popcountl(val));
46 } else {
47 return static_cast<int>(__builtin_popcount(val));
48 }
49#endif
50 }
51
52 return etl::detail::popcount_fallback(val);
53}
54
55} // namespace etl
56
57#endif // TETL_BIT_POPCOUNT_HPP
constexpr auto popcount(UInt val) noexcept -> int
Returns the number of 1 bits in the value of x.
Definition popcount.hpp:38
auto val(pin_number pin) -> etl::uint16_t
Definition gpio.hpp:37
Definition adjacent_find.hpp:8
constexpr auto is_constant_evaluated() noexcept -> bool
Detects whether the function call occurs within a constant-evaluated context. Returns true if the eva...
Definition is_constant_evaluated.hpp:16