Search code examples
c++cbytebit-fields

Reading/Writing Nibbles (without bit fields) in C/C++


Is there an easy way to read/write a nibble in a byte without using bit fields? I'll always need to read both nibbles, but will need to write each nibble individually.

Thanks!


Solution

  • Use masks :

    char byte;
    byte = (byte & 0xF0) | (nibble1 & 0xF); // write low quartet
    byte = (byte & 0x0F) | ((nibble2 & 0xF) << 4); // write high quartet
    

    You may want to put this inside macros.