Software & Finance





Java - Reverse the Bits in a Number





Here is the Java Source code to reverse the bits in the given number.

 

Source Code


import java.io.*;

 

 

class ReverseNumber {  

 

 

      public static long ReverseInt(long number)

      {

            int result = 0;

            int msbpos = 4 * 8 - 1;

 

            while(true)

            {

                  if( (number & 0x01) == 1)

                  {

                        result |= (0x01 << msbpos);

                  }

                  number >>= 1;

                  msbpos--;

                  if(msbpos < 0)

                        break;

            }

            return result;

      }

 

 

    public static void main(String[] args) {

 

            String inpstring = "";

            InputStreamReader input = new InputStreamReader(System.in);

            BufferedReader reader = new BufferedReader(input);

 

            try

            {

                  System.out.print("Enter a Number to reverse its bits:");

                  inpstring = reader.readLine();

                  long number = Long.parseLong(inpstring, 16);

                  long rnumber = ReverseInt(number);

                  System.out.println(Long.toString(number, 2) + "\n" + Long.toString(rnumber, 2));

                  System.out.println(Long.toString(number, 16) + "\n" + Long.toString(rnumber, 16));

            }

            catch (Exception e)

            {

                  e.printStackTrace();

            }

    }

}

 

Output


D:\Program Files\Java\jdk1.6.0_23\bin>Java ReverseNumber

Enter a Number to reverse its bits:A5A5C2C2

10100101101001011100001011000010

1000011010000111010010110100101

a5a5c2c2

4343a5a5