Java Short reverseBytes()方法及示例

来源:这里教程网 时间:2026-02-17 21:09:50 作者:

Java Short reverseBytes()方法及示例

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

语法:

public static short reverseBytes(short a)

参数。该方法需要一个短类型的参数a,其字节要被反转。

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

举例说明

输入 : 75
输出 : 1258291200
解释:
考虑short a = 75
二进制表示法 = 1001011
一个比特的数量=4
反转字节后 = 1258291200

输入 : -43
输出 : -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 = 61After 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 = -45After reversing the bytes :  New value : -11265

相关推荐