Tuesday, December 20, 2011

Swap pair of bits in a byte

We have an arbitrary 8-bit binary number e.g., 11101101
We  have to swap all the pair of bits like:

Before swapping: 11-10-11-01 After swapping: 11-01-11-10

Strategy:

In pseudo-code:

x = ((x & 0b10101010) >> 1) | ((x & 0b01010101) << 1)

It works by handling the low bits and high bits of each bit-pair separately and then combining the result:

    The expression x & 0b10101010 extracts the high bit from each pair, and then >> 1 shifts it to the low bit position.
    Similarly the expression (x & 0b01010101) << 1 extracts the low bit from each pair and shifts it to the high bit position.
    The two parts are then combined using bitwise-OR.

Since not all languages allow you to write binary literals directly, you could write them in for example hexadecimal:

Binary        Hexadecimal  Decimal
0b10101010    0xaa         170
0b01010101    0x55         85

2 comments:

  1. int smallest_of_3_minus(int x, int y, int z)
    {
    int c = 0;
    while ( x && y && z )
    {
    x--; y--; z--; c++;
    }
    return c;
    }

    ReplyDelete
  2. int smallest_of_3_bit(int x, int y, int z)
    {
    return min_of_2_bit(x, min_of_2_bit(y, z));
    }

    int min_of_2_bit(int x, int y)
    {
    return y + ((x - y) & ((x - y) >>
    (sizeof(int) * CHAR_BIT - 1)));
    }

    ReplyDelete