Saturday, July 16, 2016

Swap odd bit and even bit of unsigned 32 bit integer

July 16, 2016

Work on bit manipulation is so much fun. Julia likes to get workout on bit manipulation, and work on the code one by one.

  This blog has everything, but it is hard to know what is going on.
http://juliachencoding.blogspot.ca/2016/07/reverse-unsigned-32-bit-integer.html


For the first step, you would do:
    x = ((x & 0x55555555) << 1) | ((x & 0xAAAAAAAA) >> 1);
Julia's comment:  5 minutes workout - how to swap odd bit and even bits?
  5 = 101
How to swap odd bit and even bits?
In other words, odd bit becomes even bit; even bit goes to odd bit

First, odd bit shifts to left; even bit shifts to right.

32 bits: 0101 0101 0101 0101 0101 0101 0101 0101
  all odd bit number in x:
    x & 0x55555555
 left shift 1 bit: 
 (x & 0x55555555) << 1)

So, even bits shift to right; 
  A in bits presentation: 1010 
all even bit number in x:
  x & 0xAAAAAAAA

After the swap, the new value is 
   x = ((x & 0x55555555) << 1) | ((x & 0xAAAAAAAA) >> 1);
-- end of Julia's comment --

No comments:

Post a Comment