Java program to swap two bits of a 32-bit integer number

Given/input an integer number, we have to swap two bits of a 32-bit integer number.
Submitted by Nidhi, on March 12, 2022

Problem Solution:

In this program, we will read an integer number and bit positions from the user. Then we will swap bits at given positions in binary representation and print the result.

Program/Source Code:

The source code to swap two bits of a 32-bit integer number is given below. The given program is compiled and executed successfully.

// Java program to swap two bits of a 
// 32-bit integer number

import java.util.Scanner;

public class Main {
  public static void main(String[] args) {
    Scanner SC = new Scanner(System.in);

    int num = 0;
    int pos1 = 0;
    int pos2 = 0;

    int i = 0;

    System.out.printf("Enter Number: ");
    num = SC.nextInt();

    System.out.printf("Enter position1: ");
    pos1 = SC.nextInt();

    System.out.printf("Enter position2: ");
    pos2 = SC.nextInt();

    System.out.printf("Binary number before swapping bits: \n");

    for (i = 31; i >= 0; i--) {
      if ((num & (1 << i)) != 0)
        System.out.printf("1");
      else
        System.out.printf("0");
    }

    if ((((num & (1 << pos1)) >> pos1) ^ ((num & (1 << pos2)) >> pos2)) != 0) {
      num ^= (1 << pos1);
      num ^= (1 << pos2);
    }

    System.out.printf("\nResult is: %d\n", num);
    System.out.printf("Binary number after swapping bits: \n");

    for (i = 31; i >= 0; i--) {
      if ((num & (1 << i)) != 0)
        System.out.printf("1");
      else
        System.out.printf("0");
    }
    System.out.printf("\n");
  }
}

Output:

Enter Number: 2730
Enter position1: 1
Enter position2: 2
Binary number before swapping bits: 
00000000000000000000101010101010
Result is: 2732
Binary number after swapping bits: 
00000000000000000000101010101100

Explanation:

In the above program, we imported the java.util.Scanner package to read the variable's value 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 read an integer number and bit positions from the user. Then we swapped bits at given positions in binary numbers and printed the result.

Java Basic Programs »



Related Programs




Comments and Discussions!

Load comments ↻






Copyright © 2024 www.includehelp.com. All rights reserved.