Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swapping pair of bits in a Byte

I have an arbitrary 8-bit binary number e.g., 11101101

I have to swap all the pair of bits like:

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

I was asked this in an interview !

like image 686
RaviPathak Avatar asked Sep 21 '10 08:09

RaviPathak


2 Answers

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
like image 175
Mark Byers Avatar answered Sep 28 '22 05:09

Mark Byers


  1. Make two bit masks, one containing all the even bits and one containing the uneven bits (10101010 and 01010101).
  2. Use bitwise-and to filter the input into two numbers, one having all the even bits zeroed, the other having all the uneven bits zeroed.
  3. Shift the number that contains only even bits one bit to the left, and the other one one bit to the right
  4. Use bitwise-or to combine them back together.

Example for 16 bits (not actual code):

short swap_bit_pair(short i) {
    return ((i & 0101010110101010b) >> 1) | ((i & 0x0101010101010101b) << 1));
}
like image 45
tdammers Avatar answered Sep 28 '22 05:09

tdammers