Last active
July 15, 2024 14:13
-
-
Save jakubtomsu/f8169ebd67034cacf58d0f7b091f431b to your computer and use it in GitHub Desktop.
Super simple single-header bitarray example in C
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Simple bitarray example | |
// ----------------------- | |
// Warning: no bounds checking | |
// Usually I'd use 'uint8_t' instead of an 'char' and 'size_t' instead of an 'int', | |
// but this way it can be copied anywhere without worrying about includes. | |
static inline int bitarray_get(const char* bitarray, const int index) { | |
return ((bitarray[index / 8]) >> (index % 8)) & 1; | |
} | |
static inline void bitarray_set1(char* bitarray, const int index) { | |
bitarray[index / 8] |= (1 << (index % 8)); | |
} | |
static inline void bitarray_set0(char* bitarray, const int index) { | |
bitarray[index / 8] &= ~(1 << (index % 8)); | |
} | |
// Note: the compiler is good at optimizing the bitwise math used in this example. | |
// 'bitarray_get' function would be optimized into something like this: | |
// return ((bitarray[index >> 3]) >> (index & 7)) & 1; | |
// This works on Clang and GCC even without optimizations disabled. |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment