Search code examples
cbitbit-fields

How to make an array of bits?


I want to make an array of int bit fields where each int has one bit, meaning that all of the numbers will be 1 or 0, how can I code that?

I tried

struct bitarr {
    int arr : 1[14];
};

but that doesn't compile and I don't think that this is the way


Solution

  • You can not do array of these bits. Instead, create single 16-bit variable for your bits, then instead of accessing it as i[myindex] you can access it as bitsVariable & (1 << myindex).

    To set bit, you can use:

    bitsVariable |= 1 << myindex;
    

    To clear bit, you can use:

    bitsVariable &= ~(1 << myIndex);
    

    To check bit, you can use:

    if (bitsVariable & (1 << myIndex)) {
        //Bit is set
    } else {
        //Bit is not set
    }