2 * bitops.h - inline functions for bit manipulation
4 * The following copying information applies to this specific source code file:
6 * Written in 2014-2016 by Eric Biggers <ebiggers3@gmail.com>
8 * To the extent possible under law, the author(s) have dedicated all copyright
9 * and related and neighboring rights to this software to the public domain
10 * worldwide via the Creative Commons Zero 1.0 Universal Public Domain
11 * Dedication (the "CC0").
13 * This software is distributed in the hope that it will be useful, but WITHOUT
14 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
15 * FOR A PARTICULAR PURPOSE. See the CC0 for more details.
17 * You should have received a copy of the CC0 along with this software; if not
18 * see <http://creativecommons.org/publicdomain/zero/1.0/>.
21 #ifndef _WIMLIB_BITOPS_H
22 #define _WIMLIB_BITOPS_H
24 #include "wimlib/compiler.h"
25 #include "wimlib/types.h"
28 * Bit Scan Reverse (BSR) - find the 0-based index (relative to the least
29 * significant bit) of the *most* significant 1 bit in the input value. The
30 * input value must be nonzero!
33 static forceinline unsigned
37 return compiler_bsr32(v);
40 while ((v >>= 1) != 0)
46 static forceinline unsigned
50 return compiler_bsr64(v);
53 while ((v >>= 1) != 0)
59 static forceinline unsigned
60 bsrw(machine_word_t v)
62 STATIC_ASSERT(WORDBITS == 32 || WORDBITS == 64);
70 * Bit Scan Forward (BSF) - find the 0-based index (relative to the least
71 * significant bit) of the *least* significant 1 bit in the input value. The
72 * input value must be nonzero!
75 static forceinline unsigned
79 return compiler_bsf32(v);
82 for (bit = 0; !(v & 1); bit++, v >>= 1)
88 static forceinline unsigned
92 return compiler_bsf64(v);
95 for (bit = 0; !(v & 1); bit++, v >>= 1)
101 static forceinline unsigned
102 bsfw(machine_word_t v)
104 STATIC_ASSERT(WORDBITS == 32 || WORDBITS == 64);
111 /* Return the log base 2 of 'n', rounded up to the nearest integer. */
112 static forceinline unsigned
117 return 1 + bsrw(n - 1);
120 /* Round 'n' up to the nearest power of 2 */
121 static forceinline size_t
122 roundup_pow_of_2(size_t n)
124 return (size_t)1 << ilog2_ceil(n);
127 #endif /* _WIMLIB_BITOPS_H */