The source code to swap the first and second bits of an integer number is given below. The given program is compiled and executed successfully.
// Java program to swap 1st and 2nd bits
// of an integer number
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
byte data = 10;
byte bit_1 = 0;
byte bit_2 = 0;
byte xor_of_bit = 0;;
//Get 1st bit from data
bit_1 = (byte)((data >> 1) & 1);
//Get 2nd bit from data
bit_2 = (byte)((data >> 2) & 1);
//Now swap bit_1 and bit_2.
xor_of_bit = (byte)(bit_1 ^ bit_2);
data = (byte)(data ^ (xor_of_bit << 1 | xor_of_bit << 2));
System.out.printf("After swapping the bit1 and bit2: %02d", data);
}
}
Output:
After swapping the bit1 and bit2: 12
Explanation:
In the above program, we imported the "java.util.Scanner" package to read input from the user. And, created a public class Main. It contains a static method main().
The main() method is an entry point for the program. Here, we created an integer variable initialized with 10. Then we swapped 1st and 2nd bits of number and printed the result.
Binary of 10: 0000 1010
After swapping of bit 1 and 2
Binary will be: 0000 1100
Output number will be: 12
Program/Source Code:
The source code to swap the first and second bits of an integer number is given below. The given program is compiled and executed successfully.
Output:
Explanation:
In the above program, we imported the "java.util.Scanner" package to read input from the user. And, created a public class Main. It contains a static method main().
The main() method is an entry point for the program. Here, we created an integer variable initialized with 10. Then we swapped 1st and 2nd bits of number and printed the result.