Short reverseBytes() in Java with Examples


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.

filter_none

edit
close

play_arrow

link
brightness_4
code

// 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));
    }
}

chevron_right


Output:

Original value = 61
After reversing the bytes :  
New value : 15616

Program 2: For a negative number.

filter_none

edit
close

play_arrow

link
brightness_4
code

// 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));
    }
}

chevron_right


Output:

Original value = -45
After reversing the bytes :  
New value : -11265


My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.