Let us say that byte1 = 00001111
, and byte2 = 11110000
. How would I take the second half of byte1
, then take the first half of byte2
and combine them to get one byte of value 11111111
. I have done some research, but I just cannot seem to wrap my head around bitmasks and shifting.
Asked
Active
Viewed 1,162 times
1

Hobbs2000
- 311
- 1
- 6
- 19
1 Answers
2
If it's guaranteed that the "spare" bits are all zeroes, you can just OR
together the two bytes, since A or 0 == A
(see below)
If that's not guaranteed, you need (byte1 AND 0x0f) OR (byte2 AND 0xf0)
.
The AND
operations set the unwanted bits to zero (since A AND 0 == 0
) and then the OR
operation combines the bytes, as above.
ABCDXXXX XXXXEFGH
AND 11110000 (0xf0) AND 00001111 (0x0f)
-------- --------
= ABCD0000 = 0000EFGH
and then
ABCD0000
OR 0000EFGH
--------
= ABCDEFGH
No bit shifts are required because the bits you want to keep are already in the correct bit positions.

Alnitak
- 334,560
- 70
- 407
- 495
-
Where did you get the hex 0x0f? – Hobbs2000 Feb 04 '16 at 17:39
-
@Hobbs2000 That's just the hex for `0b00001111` – Alnitak Feb 04 '16 at 23:12