Skip to content
Related Articles

Related Articles

Short reverseBytes() in Java with Examples
  • Last Updated : 05 Dec, 2018


The reverseBytes() method of Short class is a built in method in Java which is used to return the value obtained by reversing the order of the bytes in the two’s complement representation of the specified short value.

Syntax :

public static short reverseBytes(short a)

Parameter: The method takes one parameter a of short type whose bytes are to be reversed.

Return Value: The method will return the value obtained by reversing the bytes in the specified short value.

Examples:



Input: 75
Output: 1258291200
Explanation:
Consider an short a = 75 
Binary Representation = 1001011
Number of one bit = 4 
After reversing the bytes = 1258291200

Input: -43
Output: -704643073

Below programs illustrate the Short.reverseBytes() method:

Program 1: For a positive number.




// Java program to illustrate the
// Short.reverseBytes() method
  
import java.lang.*;
  
public class Geeks {
  
    public static void main(String[] args)
    {
  
        // Create a Short instance
        short a = 61;
  
        // Print the value before reversal of Bytes
        System.out.println("Original value = " + a);
  
        // Reverse the bytes in the specified short value
        // Using reverseBytes() method
        System.out.println("After reversing the bytes :  \n"
                           + "New value : "
                           + Short.reverseBytes(a));
    }
}
Output:
Original value = 61
After reversing the bytes :  
New value : 15616

Program 2: For a negative number.




// Java program to illustrate the
// Short.reverseBytes() method
  
import java.lang.*;
  
public class Geeks {
  
    public static void main(String[] args)
    {
  
        // Create a Short instance
        short a = -45;
  
        // Print the value before reversal of Bytes
        System.out.println("Original value = " + a);
  
        // Reverse the bytes in the specified short value
        // Using reverseBytes() method
        System.out.println("After reversing the bytes :  \n"
                           + "New value : "
                           + Short.reverseBytes(a));
    }
}
Output:
Original value = -45
After reversing the bytes :  
New value : -11265

Attention reader! Don’t stop learning now. Get hold of all the important Java Foundation and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.

My Personal Notes arrow_drop_up
Recommended Articles
Page :