/* bitfield.h - bitfield macros */ /* * PUBLIC DOMAIN - NO COPYRIGHT CLAIMED - Jonathan Mayo - July 2005 * * Updated January 2010 */ #ifndef BITFIELD_H #define BITFIELD_H #include /* return in type sized elements to create a bitfield of 'bits' bits */ #define BITFIELD(bits, type) (((bits)+(CHAR_BIT*sizeof(type))-1)/(CHAR_BIT*sizeof(type))) /* size of a word */ #define BITWORDSZ(x) (CHAR_BIT*sizeof *(x)) /* set bit position 'bit' in bitfield x */ #define BITSET(x, bit) (x)[(bit)/(BITWORDSZ(x))]|=1ul<<((bit)%BITWORDSZ(x)) /* clear bit position 'bit' in bitfield x */ #define BITCLR(x, bit) (x)[(bit)/(BITWORDSZ(x))]&=~(1ul<<((bit)%BITWORDSZ(x))) /* toggle bit position 'bit' in bitfield x */ #define BITINV(x, bit) (x)[(bit)/(BITWORDSZ(x))]^=1ul<<((bit)%BITWORDSZ(x)) /* return a large non-zero number if the bit is set, zero if clear */ #define BITTEST(x, bit) ((x)[(bit)/(BITWORDSZ(x))]&(1ul<<((bit)%BITWORDSZ(x)))) /* checks that bit is in range for bitfield x. * doesn't work if x is a pointer, must be an array. */ #define BITRANGE(x, bit) ((bit)<(sizeof(x)*CHAR_BIT)) /* example/test program #include #include #include "bitfield.h" int main(int argc, char **argv) { unsigned long bits[BITFIELD(100,unsigned long)] = {0}; int i; printf("size=%d bytes (%d bits)\n",sizeof bits, CHAR_BIT * sizeof bits); for(i=1;i