Java program to swap all odd and even bits

Actually, 0 and 1 can do a lot. In fact, the reason behind today’s technology is, of course, 0 and 1. Any field, say, for instance, Networking, relies upon binary. If one of the bits in a binary string is swapped, it is called an Error in the jargon of Networking.

For example, consider the Java program below to swap all odd and even bits. It is just one of many ways of swapping odd with even bits.

import java.util.Scanner;
class BinaryString {
    private char[] binaryString = null;
    public BinaryString(int n) {
        this.binaryString = Integer.toBinaryString(n).toCharArray();
    }
    public void swapBits() {
        for (int i = 1; i < binaryString.length; i = i + 2) {
            char currentBit = binaryString[i];
            char prevBit = binaryString[i-1];
            binaryString[i-1] = currentBit;
            binaryString[i] = prevBit;
        }
    }
    public String getString(){ 
        return new String(this.binaryString);
    }
}
class binarySwapExample {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        System.out.print("Enter an integer: ");
        int number = in.nextInt();
        BinaryString binarystring = new BinaryString(number);
        System.out.println("Binary representation of "+number+": "+binarystring.getString());
        binarystring.swapBits();
        System.out.println("After swapping odd bits with even ones: "+binarystring.getString());
        in.close();
    }
}

The method toBinaryString of class Integer returns a string representation of the integer argument. The method toCharArray of class String returns the characters in the string on which this method is invoked, as an array.

swapBits 21

For example,number = 21. The binary representation will be 1 0 1 0 1.

Let binaryString = 10101. (length of binaryString = 5)

i = 1, i < 5
        prevBit = 1
        currentBit = 0      
        binaryString[0] = currentBit
        binaryString[1] = prevBit
binaryString = 01101

i = 3, i < 5 (i = 3 since, the loop increments i by 2 every iteration)
        prevBit = 1
        currentBit = 0      
        binaryString[2] = currentBit
        binaryString[3] = prevBit
binaryString = 01011

i = 5, i !< 5 (so the loop terminates)
binaryString = 01011

If the above example is run, it will print the output given below,

Enter an integer: 21
Binary representation of 21: 10101
After swapping odd bits with even ones: 01011

Leave a Reply

Your email address will not be published. Required fields are marked *