Search code examples
bit-shift

How to use bitwise to convert a 4-bit binary number to an 8-bit binary number?



My goal is to write a bitwise expression to represent an 8-bit number in the right column by a 4-bit number in the left column. Hope someone will help me to solve this question. Thanks very much!

4 bits         8 bits
0001         00000011
0010         00001100
0011         00001111
0100         00110000
0101         00110011
0110         00111100
0111         00111111
1000         11000000
1001         11000011
1010         11001100
1011         11001111
1100         11110000
1101         11110011
1110         11111100
1111         11111111

Solution

  • The straightforward way is from a 4-bit word dcba to first generate 0d0c0b0a by shifting each bit in the right place:

    t = (x & 0b0001) | ((x & 0b0010) << 1) | ((x & 0b0100) << 2) | ((x & 0b1000) << 3)
    

    and then duplicate the bits:

    return t | (t << 1)
    

    A trickier alternative that needs fewer instructions is to first introduce a gap that leaves a and c in the right place:

    t = (x | (x << 2)) & 0b00110011
    

    and then shift b and d and introduce the duplication:

    return ((t + (t | 0b1010101)) ^ 0b1010101) & 0b11111111
    

    (the final & is not needed if the data type is limited to 8 bits anyway).