Q:

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

belongs to collection: Java Basic Programs

0

Java program to swap two bits of a 32-bit 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 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

 

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 a given number is the power ... >>
<< Java program to count the number of leading zeros ...