2022-04-19 16:27:52 +01:00
|
|
|
// This file is part of the mcl project.
|
|
|
|
// Copyright (c) 2022 merryhime
|
|
|
|
// SPDX-License-Identifier: MIT
|
|
|
|
|
|
|
|
#pragma once
|
|
|
|
|
|
|
|
#include <bitset>
|
|
|
|
|
|
|
|
#include "mcl/bitsizeof.hpp"
|
|
|
|
#include "mcl/concepts/bit_integral.hpp"
|
|
|
|
#include "mcl/stdint.hpp"
|
|
|
|
|
|
|
|
namespace mcl::bit {
|
|
|
|
|
|
|
|
template<BitIntegral T>
|
2022-07-10 10:10:04 +01:00
|
|
|
inline size_t count_ones(T x)
|
|
|
|
{
|
2022-04-19 16:27:52 +01:00
|
|
|
return std::bitset<bitsizeof<T>>(x).count();
|
|
|
|
}
|
|
|
|
|
|
|
|
template<BitIntegral T>
|
2022-07-10 10:10:04 +01:00
|
|
|
constexpr size_t count_leading_zeros(T x)
|
|
|
|
{
|
2022-04-19 16:27:52 +01:00
|
|
|
size_t result = bitsizeof<T>;
|
|
|
|
while (x != 0) {
|
|
|
|
x >>= 1;
|
|
|
|
result--;
|
|
|
|
}
|
|
|
|
return result;
|
|
|
|
}
|
|
|
|
|
|
|
|
template<BitIntegral T>
|
2022-07-10 10:10:04 +01:00
|
|
|
constexpr int highest_set_bit(T x)
|
|
|
|
{
|
2022-04-19 16:27:52 +01:00
|
|
|
int result = -1;
|
|
|
|
while (x != 0) {
|
|
|
|
x >>= 1;
|
|
|
|
result++;
|
|
|
|
}
|
|
|
|
return result;
|
|
|
|
}
|
|
|
|
|
|
|
|
template<BitIntegral T>
|
2022-07-10 10:10:04 +01:00
|
|
|
constexpr size_t lowest_set_bit(T x)
|
|
|
|
{
|
2022-04-19 16:27:52 +01:00
|
|
|
if (x == 0) {
|
|
|
|
return bitsizeof<T>;
|
|
|
|
}
|
|
|
|
|
|
|
|
size_t result = 0;
|
|
|
|
while ((x & 1) == 0) {
|
|
|
|
x >>= 1;
|
|
|
|
result++;
|
|
|
|
}
|
|
|
|
return result;
|
|
|
|
}
|
|
|
|
|
|
|
|
} // namespace mcl::bit
|