Search code examples
cbitbitmask

C set 3 bits for a particular number


I am trying to understand masking concept and want to set bits 24,25,26 of a uint32_t number in C.

example i have

uint32_t data =0;

I am taking an input from user of uint_8 which can be only be value 3 and 4 (011,100)

I want to set the value 011 or 110 in bits 24,25,26 of the data variable without disturbing other bits.

Thanks.


Solution

  • To set bits 24, 25, and 26 of an integer without modifying the other bits, you can use this pattern:

    data = (data & ~((uint32_t)7 << 24)) | ((uint32_t)(newBitValues & 7) << 24);
    

    The first & operation clears those three bits. Then we use another & operation to ensure we have a number between 0 and 7. Then we shift it to the left by 24 bits and use | to put those bits into the final result.

    I have some uint32_t casts just to ensure that this code works properly on systems where int has fewer than 32 bits, but you probably won't need those unless you are programming embedded systems.