Sunday, October 21, 2012

BitManipulation2

Q2. Write a program to swap odd and even bits in integer, what is the minimum number of instructions required?
(eg, bit 0 and bit 1 are swapped, bit 2 and bit 3 are swapped, etc).

Answer:

public class BitManipulation2 {
    public static int swapOddEvenBits(int n) {
        return (((n & 0xaaaaaaaa) >> 1) | ((n & 0x55555555) << 1));
    }
   
    public static void main(String[] args){
        // for 10: binary representation = 0000 0000 0000 1010
        // So output should be:                  0000 0000 0000 0101 (i.e 5)
        System.out.println(swapOddEvenBits(10));
        System.out.println(swapOddEvenBits(15));
    }
}

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.