Created
March 27, 2012 18:27
-
-
Save gandaro/2218750 to your computer and use it in GitHub Desktop.
A simple bit array implementation.
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
#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)); | |
} |
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
/* `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); |
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
#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; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
That rocks !
Everything in the header may be possible too: