Monday 6 May 2013

tit bits - SWAPPING ADJACENT BITS


If   X = 1100 1010 

Result will be "1100 0101"

Left->Right

1 swapped with adjacent 1
0 swapped with adjacent 0
0 swapped with adjacent 1
0 swapped with adjacent 1

How to do:

1. Create an even bit pattern and an odd bit pattern "0xAA", "0x55"

2. Perform bitwise AND with x and even pattern(xeven) and odd pattern (xodd)

i.e 0x 1100 1010 & 0x 1010 1010,   0x 1100 1010 & 0x 0101 0101

3. Right shift xeven by 1,  xevenshift = xeven>>1

4. Left shift xodd by 1, xoddshift = xodd <<1

5. Perform bitwise OR between xevenshift and xoddshift

Result = xevenshift | xoddshift

No comments:

Post a Comment