
If we have mask = 0x02 = 00000010 (1 byte) then we can OR this to any word to set that bit position: target = 1 0 1 1 0 1 0 0 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. To set a bit, you need to OR the target word with another word with 1 in that specific bit position and 0 in all other with the the target. It simply takes the index, uses the lower three bits of the index to identify eight 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. 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) |= (0x01 >3] &= ~(0x01 >3]) & (0x01 << ((x) & 0x07))) != 0) Setting a bit is okay, but more than one bit, I am finding it little difficult. How do I replace only certain bit/bits in a 32/64 bit fields without affecting the whole data of the field using C?.How do I go about doing read, modify, and write?.If I do this, the value at bit positions 5 and 6 will become 11 (0x3), not 01 (0x1) which I wanted. Reg_data |= 1 << shift // In this case, 'shift' is 5 (Right now it is 10, which is 2 in decimal, and I want to replace it to 1 e 01) without other bits getting affected and write back the register with only bits 5 and 6 modified (so it becomes 126 after changing). Now I want to change the value at bit position 5 and 6 to 01. Now, when I read the register, I get say value 0x146 (0001 0 10 0 0110). I have a 64-bit register where bits 5 and 6 can take values 0, 1, 2, and 3. I wanted to replace bit/bits (more than one) in a 32/64 bit data field without affecting other bits.
