Reputation: 2952
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?
Upvotes: 2
Views: 7670
Reputation: 11
Following Example shows how to set a nibble by an example of swapping two nibbles :
Make two copies of the original byte.
char orig = 'A';
char lower = orig;
char upper = orig;`
Mask the upper and lower nibbles respectively and bit shift each to opposite sides by 4 bits.
lower &= 0x0F;
lower = lower << 4;
upper &= 0xF0;
upper = upper >> 4;
upper |= upper | lower;
The last line ORs both numbers by uniting both nibbles to yield a swapped nibble.
The test character is 'A' which is 65 in ASCII and binary 01000001. The swapping of the two nibbles (0100 and 0001) would yield 00010100 which is 20 in Decimal.
Following part validates the answer :
printf("ans : %d",upper);
Upvotes: 1
Reputation: 727137
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);
Upvotes: 2