Search code examples
c++binarybitwise-operators

Set 4 bits of a specific byte


Let's say I have the following bytes:

char* frame = new char[6];

That would result in this:

00000000 00000000 00000000 00000000 00000000 00000000

Now I take the first byte, frame[0] and set its last 4 bits like this:

frame[0] |= 1 << 7
frame[0] |= 1 << 6
frame[0] |= 1 << 5
frame[0] |= 1 << 4

The first byte now:

11110000

I'm writing a function which is given a number between 0x0 and 0xF. The number should be written into the first 4 bits of the byte.

Example:

void setByte(char value)
{
    // ... ??
}

setByte(0xD) // 0xD = 00001101;

After the function has finished the byte shall now look like this:

11111101

I'm not sure how I can do this - maybe it is possible to "copy" the last 4 bits into the other byte?


Solution

  • The trick to setting a nibble is to clear the desired four bits first, and then to OR in the new value.

    Use 0xF0 mask to clear out the lower nibble; for the upper nibble the mask is 0x0F.

    char setLowerNibble(char orig, char nibble) {
        char res = orig;
        res &= 0xF0; // Clear out the lower nibble
        res |= (nibble & 0x0F); // OR in the desired mask
        return res;
    }
    
    char setUpperNibble(char orig, char nibble) {
        char res = orig;
        res &= 0x0F; // Clear out the upper nibble
        res |= ((nibble << 4) & 0xF0); // OR in the desired mask
        return res;
    }
    

    You can use it as follows:

    frame[0] = setLowerNibble(frame[0], lowerNibbleOfFrame0);
    frame[0] = setUpperNibble(frame[0], upperNibbleOfFrame0);