Alex Rivera | Logout

Swapping pair of bits in a Byte

Asked 2010-09-21T08:10:20.617
10

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 !

Edit
Report

2 Answers

6
  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));
}
answered 2010-09-21T08:17:42.417
0

The most elegant and flexible solution is, as others have said, to apply an 'comb' mask to both the even and odd bits seperately and then, having shifted them left and right respectively one place to combine them using bitwise or.

One other solution you may want to think about takes advantage of the relatively small size of your datatype. You can create a look up table of 256 values which is statically initialised to the values you want as output to your input:

const unsigned char lookup[] = { 0x02, 0x01, 0x03, 0x08, 0x0A, 0x09, 0x0B ...

Each value is placed in the array to represent the transformation of the index. So if you then do this:

unsigned char out = lookup[ 0xAA ];

out will contain 0x55

This is more cumbersome and less flexible than the first approach (what if you want to move from 8 bits to 16?) but does have the approach that it will be measurably faster if performing a large number of these operations.

answered 2012-10-22T08:24:39.530

Your Answer