简体   繁体   中英

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!

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.

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

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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM