### Question 20.8

How can I implement sets or arrays of bits?

Use arrays of `char` or `int`, with a few macros to access the desired bit at the proper index. Here are some simple macros to use with arrays of `char`:

    #include <limits.h>		/* for CHAR_BIT */

    #define BITMASK(b) (1 << ((b) % CHAR_BIT))
    #define BITSLOT(b) ((b) / CHAR_BIT)
    #define BITSET(a, b) ((a)[BITSLOT(b)] |= BITMASK(b))
    #define BITTEST(a, b) ((a)[BITSLOT(b)] & BITMASK(b))

(If you don't have `<limits.h>`, try using 8 for `CHAR_BIT`.)

References: H&S Sec. 7.6.7 pp. 211-216

Read sequentially: prev next up top

This page by Steve Summit // Copyright 1995 // mail feedback