Bitops
Bit-field macros and two helpers for unsigned integers, header-only in lfbitops.h. Masks are uint64_t, so widths 32 and 64 are defined, and a bit index must be in 0..63.
Usage#
Set, clear, toggle, and insert update an integer in place. Test and extract only read it.
uint64_t reg = 0;
LF_BIT_SET(reg, 0);
LF_BIT_INSERT(reg, 8, 8, 0xABu);
LF_BIT_CLEAR(reg, 0);
uint64_t field = LF_BIT_EXTRACT(reg, 8, 8);
if (LF_BIT_TEST(reg, 8) && field == 0xAB) {
/* bit 0 is clear; bits 8..15 hold 0xAB */
}
start must be in 0..63. A field kept intact needs width <= 64 - start, so a 64-bit field uses start == 0. A bit index or start outside 0..63 is an undefined shift. A width of 64 or more is a full mask, not a shift by 64. LF_BIT_INSERT evaluates x, start, and width twice; do not give those arguments side effects. Storing back into an integer narrower than 64 bits drops the bits that do not fit.
Functions#
lf_bit_mask#
Returns the low width bits set. Width 0 returns 0. Width 64 or more returns ~0ULL. Extract and insert use this mask.
static inline uint64_t lf_bit_mask(unsigned width);lf_is_pow2#
Returns 1 when x is a power of two, including 1. Returns 0 for 0 and for every other value.
static inline int lf_is_pow2(uint64_t x);Macros#
LF_BIT_SET, LF_BIT_CLEAR, LF_BIT_TOGGLE, LF_BIT_TEST, and LF_BIT_EXTRACT evaluate each argument once.
LF_BIT_SET / LF_BIT_CLEAR / LF_BIT_TOGGLE / LF_BIT_TEST#
Set, clear, and toggle bit i. x is a modifiable integer lvalue. Test does not modify x. Its result is x masked with that bit: 0 when the bit is clear, and the place value 1ULL << i when it is set, not a normalized 1.
#define LF_BIT_SET(x, i) ((x) |= 1ULL << (i))
#define LF_BIT_CLEAR(x, i) ((x) &= ~(1ULL << (i)))
#define LF_BIT_TOGGLE(x, i) ((x) ^= (1ULL << (i)))
#define LF_BIT_TEST(x, i) ((x) & (1ULL << (i)))LF_BIT_EXTRACT / LF_BIT_INSERT#
Extract returns the field as a uint64_t shifted down to bit 0 and does not modify x. Insert writes the low width bits of val into that field and leaves the other bits of the computed value alone. Bits of val above the field are masked off. Insert evaluates x, start, and width twice and val once. x is a modifiable integer lvalue.
#define LF_BIT_EXTRACT(x, start, width) \
(((uint64_t)(x) >> (start)) & lf_bit_mask((unsigned)(width)))
#define LF_BIT_INSERT(x, start, width, val) \
((x) = ((x) & ~(lf_bit_mask((unsigned)(width)) << (start))) | \
(((val) & lf_bit_mask((unsigned)(width))) << (start)))