Q:

Java program to swap the first and second bits of an integer number

belongs to collection: Java Basic Programs

0

Java program to swap the first and second bits of an integer number

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

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.

// 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

 

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

Java Basic Programs

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
Java program to check whether all bits of the numb... >>
<< Java program to find the number of bits required t...