In: Computer Science
Write a program that asks the user to enter an unsigned number and read it. Then swap the bits at odd positions with those at even positions and display the resulting number. For example, if the user enters the number 9, which has binary representation of 1001, then bit 0 is swapped with bit 1, and bit 2 is swapped with bit 3, resulting in the binary number 0110. Thus, the program should display 6.
COMMENT COMPLETE CODE PLEASE
As per the given problem statement what we understand is we have to first convert the given number in binary format and then separate all the even bits and odd bits, we then left shift the even bits by one position and right shift odd bits by one position, and then merge even and odd bits to get the result.
e.g. 9 = (1001) then even bits are(1000)even and odd bits are (0001)odd and if we left shift even bits by one position then we get (0100)even and right shift odd bits by one position then we get (0010)odd now we merge the both parts by binary EXOR operation then we get (0110)result i.e. 6.
To get the even bits in the given number we can AND it with 0xAAAAAAAA. And then we can right shift with >> operator.
To get the odd bits in the given number we can AND it with 0x55555555. And then we can left shift with << operator.
As you haven't mentioned any particular language in the question I will code it using JAVA as follows
import java.util.Scanner;
public class SwapEvenOddBits {
static int swapBits(int num)
{
//get even bits of number and right shift it by 1
int evenBits = num & 0xAAAAAAAA;
evenBits >>= 1;
// Get even bits of number and left shift it by 1
int oddBits = num & 0x55555555;
oddBits <<= 1;
// merge even and odd bits
int result = (evenBits | oddBits);
return result;
}
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
System.out.println("Enter the integer number");
int num = sc.nextInt();
System.out.println("Given number after swapping even odd bits is "+swapBits(num));
sc.close();
}
}
Output :