Java Integer reverseBytes()方法

来源:这里教程网 时间:2026-02-17 20:51:16 作者:

Java Integer reverseBytes()方法

java.lang.Integer.reverseBytes(int a)是一个内置的方法,它返回通过颠倒指定int值的二进制补码表示法中的字节顺序而得到的值。

语法:

public static int reverseBytes(int a)

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

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

举例说明
输入 : 75
输出 : 1258291200
解释:
考虑一个整数 a = 75
二进制表示法 = 1001011
一个比特的数量 = 4
反转字节后,我们得到 = 1258291200

Input : -43
Output : -704643073

下面的程序说明了java.lang.Integer.reverseBytes()方法:

程序1: 对于一个正数。

// Java program to illustrate the// Java.lang.Integer.reverseBytes() methodimport java.lang.*;  public class Geeks {      public static void main(String[] args)    {          int a = 61;        System.out.println(" Integral Number = " + a);          // It will return the value obtained by reversing the bytes in the        // specified int value        System.out.println("After reversing the bytes we get = " +         Integer.reverseBytes(a));    }}

输出。

Integral Number = 61After reversing the bytes we get = 1023410176

程序2: 对于一个负数。

// Java program to illustrate the// Java.lang.Integer.reverseBytes() methodimport java.lang.*;  public class Geeks {      public static void main(String[] args)    {          int a = -43;        System.out.println(" Integral Number = " + a);          // It will return the value obtained by reversing the bytes in the        // specified int value        System.out.println("After reversing the bytes we get = " +         Integer.reverseBytes(a));    }}

输出。

Integral Number = -43After reversing the bytes we get = -704643073

程序3: 对于一个十进制值和字符串。
注意: 当十进制值和字符串作为参数传递时,会返回错误信息。

// Java program to illustrate the// Java.lang.Integer.reverseBytes() methodimport java.lang.*;  public class Geeks {      public static void main(String[] args)    {          int a = 37.81;        System.out.println(" Integral Number = " + a);        // It will return the value obtained by reversing the bytes in the        // specified int value        System.out.println("After reversing the bytes we get = " +         Integer.reverseBytes(a));          a = "81"; // compile time error will be generated        System.out.println(" Integral Number = " + a);        System.out.println("After reversing the bytes we get = " +         Integer.reverseBytes(a));    }}

输出。

prog.java:9: error: incompatible types: possible lossy conversion from double to int    int a = 37.81;            ^prog.java:18: error: incompatible types: String cannot be converted to int    a = "81";        ^2 errors

相关推荐