Swapping every two bits in byte Java Solution

In the Swapping of two bits in byte in java, the output should look like something below:
Swap all the pair of bits in a byte.
Before swapping: 11-10-11-01
After swapping: 11-01-11-10

The code is written and tested in Netbeans.

Code:

import java.util.Arrays;
import java.util.Scanner;

public class bitbyte {
public static void main (String[] args) {
Scanner s=new Scanner(System.in);
System.out.println(“Enter Number of test cases:”);
int tc=s.nextInt();
for(int t=0;t<tc;t++){
System.out.println(“Enter value for bit swapping:”);
int a=s.nextInt();
int m = 0;int bin[]=new int[8],i=0;

while(a!=0){
int n=a%2;
a/=2;
bin[i]=n;
i++;
}
int j=0;

while(j<bin.length)

{
int temp=bin[j];
bin[j]=bin[j+1];
bin[j+1]=temp;
j=j+2;
}
for( i=bin.length-1;i>=0;i–){
if(bin[i]==1){
m=m+(int) Math.pow(2,i);
}
}
System.out.println(m);
}
}}

OUTPUT:

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

%d bloggers like this: