#include "lib/intmath/bits.h"
int
tor_log2(uint64_t u64)
{
int r = 0;
if (u64 >= (UINT64_C(1)<<32)) {
u64 >>= 32;
r = 32;
}
if (u64 >= (UINT64_C(1)<<16)) {
u64 >>= 16;
r += 16;
}
if (u64 >= (UINT64_C(1)<<8)) {
u64 >>= 8;
r += 8;
}
if (u64 >= (UINT64_C(1)<<4)) {
u64 >>= 4;
r += 4;
}
if (u64 >= (UINT64_C(1)<<2)) {
u64 >>= 2;
r += 2;
}
if (u64 >= (UINT64_C(1)<<1)) {
r += 1;
}
return r;
}
uint64_t
round_to_power_of_2(uint64_t u64)
{
int lg2;
uint64_t low;
uint64_t high;
if (u64 == 0)
return 1;
lg2 = tor_log2(u64);
low = UINT64_C(1) << lg2;
if (lg2 == 63)
return low;
high = UINT64_C(1) << (lg2+1);
if (high - u64 < u64 - low)
return high;
else
return low;
}
int
n_bits_set_u8(uint8_t v)
{
static const int nybble_table[] = {
0,
1,
1,
2,
1,
2,
2,
3,
1,
2,
2,
3,
2,
3,
3,
4,
};
return nybble_table[v & 15] + nybble_table[v>>4];
}