How to define and work with an array of bits in C?

前端 未结 5 1884
遇见更好的自我
遇见更好的自我 2020-11-28 20:58

I want to create a very large array on which I write \'0\'s and \'1\'s. I\'m trying to simulate a physical process called random sequential adsorption, where units of length

5条回答
  •  眼角桃花
    2020-11-28 21:47

    bitarray.h:

    #include  // defines uint32_t
    
    //typedef unsigned int bitarray_t; // if you know that int is 32 bits
    typedef uint32_t bitarray_t;
    
    #define RESERVE_BITS(n) (((n)+0x1f)>>5)
    #define DW_INDEX(x) ((x)>>5)
    #define BIT_INDEX(x) ((x)&0x1f)
    #define getbit(array,index) (((array)[DW_INDEX(index)]>>BIT_INDEX(index))&1)
    #define putbit(array, index, bit) \
        ((bit)&1 ?  ((array)[DW_INDEX(index)] |= 1<

    Use:

    bitarray_t arr[RESERVE_BITS(130)] = {0, 0x12345678,0xabcdef0,0xffff0000,0};
    int i = getbit(arr,5);
    putbit(arr,6,1);
    int x=2;            // the least significant bit is 0
    putbit(arr,6,x);    // sets bit 6 to 0 because 2&1 is 0
    putbit(arr,6,!!x);  // sets bit 6 to 1 because !!2 is 1
    

    EDIT the docs:

    "dword" = "double word" = 32-bit value (unsigned, but that's not really important)

    RESERVE_BITS: number_of_bits --> number_of_dwords
        RESERVE_BITS(n) is the number of 32-bit integers enough to store n bits
    DW_INDEX: bit_index_in_array --> dword_index_in_array
        DW_INDEX(i) is the index of dword where the i-th bit is stored.
        Both bit and dword indexes start from 0.
    BIT_INDEX: bit_index_in_array --> bit_index_in_dword
        If i is the number of some bit in the array, BIT_INDEX(i) is the number
        of that bit in the dword where the bit is stored.
        And the dword is known via DW_INDEX().
    getbit: bit_array, bit_index_in_array --> bit_value
    putbit: bit_array, bit_index_in_array, bit_value --> 0
    

    getbit(array,i) fetches the dword containing the bit i and shifts the dword right, so that the bit i becomes the least significant bit. Then, a bitwise and with 1 clears all other bits.

    putbit(array, i, v) first of all checks the least significant bit of v; if it is 0, we have to clear the bit, and if it is 1, we have to set it.
    To set the bit, we do a bitwise or of the dword that contains the bit and the value of 1 shifted left by bit_index_in_dword: that bit is set, and other bits do not change.
    To clear the bit, we do a bitwise and of the dword that contains the bit and the bitwise complement of 1 shifted left by bit_index_in_dword: that value has all bits set to one except the only zero bit in the position that we want to clear.
    The macro ends with , 0 because otherwise it would return the value of dword where the bit i is stored, and that value is not meaningful. One could also use ((void)0).

提交回复
热议问题