Swap all odd and even bits - Java
Refer:
import java.lang.*;
public class SwapAllOddsAndEvenBits {
public static void swap(int num){
String binary = Integer.toBinaryString(num);
System.out.println("Binary representation of the number = " + binary);
int swap = ((num << 1) & 0xAAAAAAAA) | ((num >> 1) & 0x55555555);
System.out.println("The number After swapping odd and even bits = " + swap);
}
public static void main(String args[]){
int num = 23;
swap(num);
}
}
Explanation:
//0xA = 1010
//0x5 = 0101
// 0,1
// 0,1,2,3,4,5,6,7,8,9
// 0,1,2,3,4,5,6,7,8,9,A,B,C,D,E,F
//0xF = 1111
// Number 010111
// Lets Swap all Even
// 101011 = 43
// Bitwise &
// 1 & 1 = 1
// 1 & 0 = 0
// 0 & 1 = 0
// 0 & 0 = 0
// 0101 << 1 = 1010
// 0101 << 2 = 0100
// 00010111 << 1 = 00101110
// 00101110 = left shift
// 10101010 = 0xAA
// 00101010 = Bitwise & = Eq1
// 00010111 >> 1 = 00001011
// 00001011 = right shift
// 01010101 = 0x55
// 00000001 = Bitwise & = Eq2
// Eq1 | Eq2
// 00101010
// 00000001
// 00101011 = Bitwise or
- https://github.com/mirandaio/interview-questions/blob/master/bit_manipulation/SwapOddEvenBits.java
- http://practice.geeksforgeeks.org/problems/swap-all-odd-and-even-bits/0
- http://www.geeksforgeeks.org/swap-all-odd-and-even-bits/
Program:
import java.lang.*;
public class SwapAllOddsAndEvenBits {
public static void swap(int num){
String binary = Integer.toBinaryString(num);
System.out.println("Binary representation of the number = " + binary);
int swap = ((num << 1) & 0xAAAAAAAA) | ((num >> 1) & 0x55555555);
System.out.println("The number After swapping odd and even bits = " + swap);
}
public static void main(String args[]){
int num = 23;
swap(num);
}
}
Explanation:
//0xA = 1010
//0x5 = 0101
// 0,1
// 0,1,2,3,4,5,6,7,8,9
// 0,1,2,3,4,5,6,7,8,9,A,B,C,D,E,F
//0xF = 1111
// Number 010111
// Lets Swap all Even
// 101011 = 43
// Bitwise &
// 1 & 1 = 1
// 1 & 0 = 0
// 0 & 1 = 0
// 0 & 0 = 0
// 0101 << 1 = 1010
// 0101 << 2 = 0100
// 00010111 << 1 = 00101110
// 00101110 = left shift
// 10101010 = 0xAA
// 00101010 = Bitwise & = Eq1
// 00010111 >> 1 = 00001011
// 00001011 = right shift
// 01010101 = 0x55
// 00000001 = Bitwise & = Eq2
// Eq1 | Eq2
// 00101010
// 00000001
// 00101011 = Bitwise or
Comments
Post a Comment