Read / write Nibbles (no bit fields) in C / C ++

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

Thank!

+3
source share
3 answers

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 internal macro.

+5
source

The smallest block you can work with is one byte. If you want to control bits, you must use bitwise operators .

+1
source

- :

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

    BYTE data;
};

:

ByteNibbles byteNibbles(0xA, 0xB);

BYTE data = byteNibbles.data;
-2

Source: https://habr.com/ru/post/1751573/


All Articles