1/* @title: Bit operations */
2#pragma once
3#include <stddef.h>
4#include <stdint.h>
5
6static inline size_t popcount(size_t n) {
7 size_t count = 0;
8 while (n > 0) {
9 if (n & 1)
10 count++;
11
12 n >>= 1;
13 }
14 return count;
15}
16
17static inline size_t next_pow2(size_t x) {
18 size_t p = 1;
19 if (x == 0)
20 return 1;
21 while (p < x) {
22 if (p > (SIZE_MAX >> 1))
23 return p;
24 p <<= 1;
25 }
26 return p;
27}
28
29static inline size_t prev_pow2(size_t x) {
30 size_t p = 1;
31 if (x == 0)
32 return 1;
33 while (p <= x) {
34 if (p > (SIZE_MAX >> 1))
35 return p;
36 p <<= 1;
37 }
38 return p >> 1;
39}
40