Skip to content

Instantly share code, notes, and snippets.

@darealshinji
Created September 13, 2025 23:13
Show Gist options
  • Select an option

  • Save darealshinji/b167399488318731d1a5a37c13888d8d to your computer and use it in GitHub Desktop.

Select an option

Save darealshinji/b167399488318731d1a5a37c13888d8d to your computer and use it in GitHub Desktop.
#include <assert.h>
#include <stdint.h>
/* boolean value */
#define BIT_IS_SET(VAL, POS) \
((VAL >> (POS)) & 1)
/* unsigned number */
#define BITCOUNT(VAL) \
(sizeof(VAL) * 8)
/* function-like macros */
#define SET_BIT(VAL, POS) \
do { \
assert((POS) < BITCOUNT(VAL)); \
VAL |= (1 << (POS)); \
} while(0)
#define UNSET_BIT(VAL, POS) \
do { \
assert((POS) < BITCOUNT(VAL)); \
VAL ^= (1 << (POS)); \
} while(0)
#define INVERT_ALL_BITS(VAL) \
do { VAL = ~VAL; } while(0)
#define INVERT_BIT(VAL, POS) \
do { \
if (BIT_IS_SET(VAL, (POS))) { \
UNSET_BIT(VAL, (POS)); \
} else { \
SET_BIT(VAL, (POS)); \
} \
} while(0)
#define BITS_TO_STRING(FLAGS) \
bits_to_string(FLAGS, BITCOUNT(FLAGS))
static inline const char *bits_to_string(uint64_t flags, uint8_t size)
{
static char buf[65] = {0};
assert(size <= 64);
for (uint8_t i = size; i > 0; --i, flags >>= 1) {
buf[i-1] = (flags & 1) ? '1' : '0';
}
return buf;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment