Home /
Expert Answers /
Computer Science /
1-4-points-write-a-java-program-to-swap-all-bits-in-odd-positions-with-bits-in-even-positions-pa850
(Solved):
1. (4 points) Write a Java program to swap all bits in odd positions with bits in even positions. ...
1. (4 points) Write a Java program to swap all bits in odd positions with bits in even positions. The following is a sample output: User enters 682, which is 1010101010 in binary and the output is \( 0101010101 . \) You should swap the bit at the \( i_{\text {th }} \) position with the bit at the \( i_{t h-1} \) position, for \( i>0 \) and \( i \leq w-1 \), where \( w \) is the number of bits. So, you swap the bit at position 0 with the bit at position 1, the bit at position 2 with the bit at position 3 , and so on. Examples: Enter a Number: 4 User Entered: 0100 Bits Swapped: 8 (1000) Enter a Number: 1927 User Entered: 011110000111 Bits Swapped: 2891 (101101001011) Enter a Number: -2147483648 User Entered: 10000000000000000000000000000000 Bits Swapped: 1073741824 (01000000000000000000000000000000)
- Use a mask and bit-wise logic operation to extract the bits at odd positions. - Use a mask and bit-wise logic operation to extract the bits at even positions. - Shift and combine the bit vectors (think to which direction each bit vector should be shifted, and how to combine those 2 vectors) Note: Leading zeros may not be displayed when treating results as integers. For example, treating 0101010101 as an integer, will not produce a leading zero, i.e. the output will be 101010101 which is acceptable. You can use the Java function Integer.toBinaryString (iput) to visualize the binary form of a number.
Code: import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner sc = new Scanner(System.in); System.out.print("Enter a Number: "); int decimal = sc.nextInt(); St