Skip to content

Instantly share code, notes, and snippets.

@WOLOHAHA
Created July 27, 2014 05:54
Show Gist options
  • Select an option

  • Save WOLOHAHA/ccdc3bf4f78cecf8ca50 to your computer and use it in GitHub Desktop.

Select an option

Save WOLOHAHA/ccdc3bf4f78cecf8ca50 to your computer and use it in GitHub Desktop.
Write a program to swap odd and even bits in an integer with as few instructions as possible (e.g., bit 0 and bit! are swapped, bit 2 and bit 3 are swapped, and so on).
package POJ;
public class Main{
/**
*
* 5.6 Write a program to swap odd and even bits in an integer with as few instructions
* as possible (e.g., bit 0 and bit! are swapped, bit 2 and bit 3 are swapped, and so on).
*
*
*/
public static void main(String[] args) {
Main so = new Main();
System.out.println(so.swapBits(4));
}
public int swapBits(int n){
return (((n&0xaaaaaaaa)>>1)|((n&0x55555555)<<1));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment