Java Long reverseBytes() Method

Java reverseBytes() method is a part of the Long class of the java.lang package. This method is used to return the value which is obtained by reversing the order of the bytes of the two's complement binary representation of the long value passed.


public static long reverseBytes(long i)  


The parameter passed is the long value whose bytes are to be reversed.


The value obtained by reversing the order of bytes of the two's complement binary representation of the parameter passed.

Example 1:

Here, a positive and a negative number is taken for a better understanding of the method. The Long.toBinaryString() method is used for representing the number in its binary equivalent.

import java.lang.Long;

public class StudyTonight
    public static void main(String[] args) 
          long a = 342;  
          long b = -23;  
          System.out.println("Original Number = " + a);             
          System.out.println("Binary Representation is = " + Long.toBinaryString(a)); //represents number to equivalent binary string 
          System.out.println("Number after reversal " + Long.reverseBytes(a)); //reversal of the bytes
          System.out.println("\n Original Number = " + b);               
          System.out.println("Binary Representation is = " + Long.toBinaryString(b));           
          System.out.println("Number after reversal = " + Long.reverseBytes(b));  

Original Number = 342
Binary Representation is = 101010110
Number after reversal 6197234562238513152

Original Number = -23
Binary Representation is = 1111111111111111111111111111111111111111111111111111111111101001
Number after reversal = -1585267068834414593

Example 2:

Here is a user-defined example where anyone using this code can put a value of his choice and get the equivalent output.

import java.util.Scanner;  

public class StudyTonight 
    public static void main(String[] args) 
           System.out.print("Enter Original Value ");  
           Scanner sc = new Scanner(;  
           long i = sc.nextLong();  
           System.out.println("Actual Number = " + i);  
           System.out.println("Binary Representation = " + Long.toBinaryString(i)); // represents the long value into its binary equivalent 
           System.out.println("After reversing = " + Long.reverseBytes(i)); //returns the value obtained by reversal of bytes
        catch(Exception e)
           System.out.println("Invalid Input");

Enter Original Value 56
Actual Number = 56
Binary Representation = 111000
After reversing = 4035225266123964416
Enter Original Value -299
Actual Number = -299
Binary Representation = 1111111111111111111111111111111111111111111111111111111011010101
After reversing = -3026700424569683969
Enter Original Value 0x445
Invalid Input

Live Example:

Here, you can test the live code example. You can execute the example for different values, even can edit and write your examples to test the Java code.