Search code examples
cbitunsigneduint8t

How to read specific bits of an unsigned int


I have an uint8_t and I need to read/write to specific bits. How would I go about doing this. Specifically what I mean is that I need to write and then later read the first 7 bits for one value and the last bit for another value.

edit: forgot to specify, I will be setting these as big endian


Solution

  • You're looking for bitmasking. Learning how to use C's bitwise operators: ~, |, &, ^ and so on will be of huge help, and I recommend you look them up.

    Otherwise -- want to read off the least significant bit?

    uint8_t i = 0x03;
    
    uint8_t j = i & 1; // j is now 1, since i is odd (LSB set)
    

    and set it?

    uint8_t i = 0x02;
    uint8_t j = 0x01;
    
    i |= (j & 1); // get LSB only of j; i is now 0x03
    

    Want to set the seven most significant bits of i to the seven most significant bits of j?

    uint8_t j = 24; // or whatever value
    uint8_t i = j & ~(1); // in other words, the inverse of 1, or all bits but 1 set
    

    Want to read off these bits of i?

    i & ~(1);
    

    Want to read the Nth (indexing from zero, where 0 is the LSB) bit of i?

    i & (1 << N);
    

    and set it?

    i |= (1 << N); // or-equals; no effect if bit is already set
    

    These tricks will come in pretty handy as you learn C.