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

2019-05-10 06:28发布

问题:

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!

回答1:

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.



回答2:

The smallest unit you can work with is a single byte. If you want to manage the bits you should use bitwise operators.



回答3:

You could create yourself a pseudo union for convenience:

union ByteNibbles
{
    ByteNibbles(BYTE hiNibble, BYTE loNibble)
    {
        data = loNibble;
        data |= hiNibble << 4;
    }

    BYTE data;
};

Use it like this:

ByteNibbles byteNibbles(0xA, 0xB);

BYTE data = byteNibbles.data;