How to combine two halves from two bytes to get a single byte

1.2k Views Asked by At

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.

1

There are 1 best solutions below

2
On

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.