Skip to content

Instantly share code, notes, and snippets.

@gandaro
Created March 27, 2012 18:27
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save gandaro/2218750 to your computer and use it in GitHub Desktop.
A simple bit array implementation.
#include "bitarray.h"
void toggle_bit(char *array, int index)
{
array[index/8] ^= 1 << (index % 8);
}
char get_bit(char *array, int index)
{
return 1 & (array[index/8] >> (index % 8));
}
/* `x+1' if `x % 8' evaluates to `true' */
#define ARRAY_SIZE(x) (x/8+(!!(x%8)))
char get_bit(char *array, int index);
void toggle_bit(char *array, int index);
#include <stdio.h>
#include "bitarray.h"
#define SIZE (58) /* amount of bits */
int main(void)
{
/* initialize empty array with the right size */
char x[ARRAY_SIZE(SIZE)] = {0};
int i;
for (i = 0; i < SIZE; i += 2)
toggle_bit(x, i);
toggle_bit(x, 56);
for (i = 0; i < SIZE; i++)
printf("%d: %d\n", i, get_bit(x, i));
return 0;
}
Copy link

ghost commented Mar 13, 2017

That rocks !

Everything in the header may be possible too:

#define ARRAY_SIZE(ARRAY)    (ARRAY / 8 + (!! (ARRAY % 8)))
#define TOGGLE_BIT(ARRAY, I) (ARRAY[I / 8] ^= 1 << (I % 8))
#define GET_BIT(ARRAY, I)    (1 & (ARRAY[I / 8] >> (I % 8))

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment