ADD: bit.h

ADD: PACK UNPACK LOWBIT
This commit is contained in:
rangersly 2025-05-07 13:03:26 +08:00
parent 216e47571b
commit 359d5ae233
2 changed files with 29 additions and 0 deletions

View File

@ -33,6 +33,7 @@
- [offsetof](./self/offsetof.h) - [offsetof](./self/offsetof.h)
- [string hash](./self/string_hash.c) - [string hash](./self/string_hash.c)
- [thread pool](./self/thread-pool.cpp) - [thread pool](./self/thread-pool.cpp)
- [BIT](./self/bit.h)
--- ---

View File

@ -0,0 +1,28 @@
#include <stdint.h>
#include <assert.h>
// Generate a mask with n bits set to 1
#define LOW_N_BITS(n) (~((~(uintmax_t)0) << (n)))
#define LOWBIT(x) ((x)&(-(x)))
// Inserts specified data into a bit segment of any type
#define PACK_BITFIELD(container, value, start_bit, width) \
((container) = (((container) & ~((((uintmax_t)1 << (width)) - 1) << (start_bit))) | \
((((uintmax_t)(value)) & (((uintmax_t)1 << (width)) - 1)) << (start_bit))))
// Security version
#define S_PACK_BITFIELD(container, value, start_bit, width) \
do { \
assert((width) > 0 && (width) < sizeof(uintmax_t)*8); \
assert((start_bit) + (width) <= sizeof(container)*8); \
PACK_BITFIELD(container, value, start_bit, width); \
} while (0)
// Extract data
#define UNPACK_BITFIELD(container, start_bit, width) \
(((container) >> (start_bit)) & (((uintmax_t)1 << (width)) - 1))
// Security version
#define S_UNPACK_BITFIELD(container, start_bit, width) \
(assert((width) > 0 && (width) < sizeof(uintmax_t)*8), \
assert((start_bit) + (width) <= sizeof(container)*8), \
(((container) >> (start_bit)) & (((uintmax_t)1 << (width)) - 1)))