Skip to content

Instantly share code, notes, and snippets.

@mjf
Created October 15, 2013 23:26
Show Gist options
  • Save mjf/7000220 to your computer and use it in GitHub Desktop.
Save mjf/7000220 to your computer and use it in GitHub Desktop.
Handle bitsets in ANSI C
/**
* cc -pedantic -ansi -pedantic-errors -Wall -Werror bitset.c -o bitset
*/
#include <stdint.h>
#include <stdlib.h>
typedef enum { /* no use for stdbool.h with ANSI C */
false = 0,
true
} bool;
bool
getbit(uint8_t * s, size_t n)
{
return s += n / 8, (bool) (!(*s & (1 << (n % 8))));
}
bool
setbit(uint8_t * s, size_t n, bool v)
{
return s += n / 8,
(bool) (v ? (*s |= 1 << (n % 8)) : (*s &= ~(1 << (n % 8))));
}
#include <stdio.h>
int
main(void)
{
uint8_t bitset[28] = { false }; /* 224 bits = (224+7)/8 = 28 */
char *bit[2] = { "true", "false" };
/* get last bit */
printf("%s\n", bit[getbit(bitset, 223) ? 1 : 0]);
/* set last bit and print it */
printf("%s\n", bit[setbit(bitset, 223, true) ? 1 : 0]);
printf("%s\n", bit[getbit(bitset, 223) ? 1 : 0]);
/* clear last bit and print it */
printf("%s\n", bit[setbit(bitset, 223, false) ? 1 : 0]);
printf("%s\n", bit[getbit(bitset, 223) ? 1 : 0]);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment