Here is a generic process which acts on a long array, considering it a long bitfield, and addresses each bit position individually:
#define set_bit(arr,x) ((arr[(x)>>3]) |= (0x01 << ((x) & 0x07))) #define clear_bit(arr,x) (arr[(x)>>3] &= ~(0x01 << ((x) & 0x07))) #define get_bit(arr,x) (((arr[(x)>>3]) & (0x01 << ((x) & 0x07))) != 0)
SimplyIt simply takes the index, uses the lower 3 btisthree bits of the index to identify 8eight different bit positions inside each location of the char array, and the upper remainder bits addresses in which array location does the bit denoted by x occur. Hope this helps.
Edit1: To To set a bit, you need to OR the target word withwith another word with 1 in that specific bit position and 0 in all other with the the target. All 0's in the other positions ensure that the existing 1's in the target are as it is during OR, and the 1 in the specific positions ensures that the target gets the 1 in that position. ifIf we have mask = 0x02 = 00000010 (1 byte) then we can OR this to any word to set that bit posposition:
target = 1 0 1 1 0 1 0 0 OR + + + + + + + + mask 0 0 0 0 0 0 1 0 --------------- answer 1 0 1 1 0 1 1 0
To clear a bit, you need to AND the target word with another word with 0 in that specific bit position and 1 in all. All 11's in all other bit positions ensure that during AND the target preserves its 0's and 1's as they were in those locations, and a 0 in the bit position to be cleared would also set that bit position 0 in the target word. ifIf we have the same mask = 0x02, then we can prepare this mask for clearing by ~mask:
mask = 0 0 0 0 0 0 1 0 ~mask = 1 1 1 1 1 1 0 1 AND . . . . . . . . target 1 0 1 1 0 1 1 0 --------------- answer 1 0 1 1 0 1 0 0