Search code examples
cconcatenation

How to combine 2 4-bit unsigned numbers into 1 8-bit number in C


I have 2 4-bit numbers (X0X1X2X3 and Y0Y1Y2Y3) and I want to combine them so that I would create an 8-bit number like that:

X0X1X2X3 
Y0Y1Y2Y3  => X0Y0X1Y1X2Y2X3Y3

I know how to concatenate them in order to create the X0X1X1X3Y0Y1Y2Y3 but I am stuck on how to compose them in the pattern explained above.

Any hints?


Solution

  • Here's a fairly direct way of performing this transformation:

    uint8_t result;
    result |= (x & 8) << 4;
    result |= (y & 8) << 3;
    result |= (x & 4) << 3;
    result |= (y & 4) << 2;
    result |= (x & 2) << 2;
    result |= (y & 2) << 1;
    result |= (x & 1) << 1;
    result |= (y & 1) << 0;