📜  Java中的简短 reverseBytes() 和示例

📅  最后修改于: 2022-05-13 01:54:30.001000             🧑  作者: Mango

Java中的简短 reverseBytes() 和示例


Short 类的reverseBytes()方法是Java中的一个内置方法,用于返回通过反转指定 short 值的二进制补码表示中的字节顺序获得的值。

句法 :

public static short reverseBytes(short a)

参数:该方法采用一个short类型的参数a ,其字节要反转。

返回值:该方法将返回指定短值中的字节反转得到的值。

例子:

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

下面的程序说明了 Short.reverseBytes() 方法:

程序 1:对于正数。

// 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));
    }
}
输出:
Original value = 61
After reversing the bytes :  
New value : 15616

程序 2:对于负数。

// 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));
    }
}
输出:
Original value = -45
After reversing the bytes :  
New value : -11265