ADVERTISEMENT
ADVERTISEMENT

Java program to reverse bits of the given number

Given/input an integer number, we have to reverse bits of the given number.
Submitted by Nidhi, on March 06, 2022

Problem Solution:

In this program, we will read an integer number and reverse the bits of the given number using bitwise operators.

Program/Source Code:

The source code to reverse bits of the given number is given below. The given program is compiled and executed successfully.

// Java program to reverse bits of 
// the given number

import java.util.Scanner;

public class Main {
  static int reverseBits(short data) {
    int revNum = 0;
    int i = 0;
    int temp = 0;

    for (i = 0; i < 16; i++) {
      temp = (data & (1 << i));
      if (temp != 0)
        revNum |= (1 << ((16 - 1) - i));
    }
    return revNum;
  }

  public static void main(String[] args) {
    short num = 0x4;
    System.out.printf("Number after reversing bits: %d", reverseBits(num));
  }
}

Output:

Number after reversing bits: 8192

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 a variable num initialized with 0x4. Then we reversed the bites of number and printed the result.

Java Basic Programs »


ADVERTISEMENT
ADVERTISEMENT


Comments and Discussions!



ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT

Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.