Java中的整数reverseBytes()方法
Java.lang.Integer.reverseBytes(int a) 是一个内置方法,它返回通过反转指定 int 值的二进制补码表示中的字节顺序获得的值。
句法 :
public static int reverseBytes(int a)
参数:该方法采用一个整数类型的参数a ,其字节要反转。
返回值:该方法将返回指定int值中的字节反转得到的值。
例子:
Input: 75
Output: 1258291200
Explanation:
Consider an integer a = 75
Binary Representation = 1001011
Number of one bit = 4
After reversing the bytes we get = 1258291200
Input: -43
Output: -704643073
下面的程序说明了Java.lang.Integer.reverseBytes() 方法:
程序 1:对于正数。
// Java program to illustrate the
// Java.lang.Integer.reverseBytes() method
import 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 = 61
After reversing the bytes we get = 1023410176
程序 2:对于负数。
// Java program to illustrate the
// Java.lang.Integer.reverseBytes() method
import 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 = -43
After reversing the bytes we get = -704643073
程序 3:对于十进制值和字符串。
注意:当十进制值和字符串作为参数传递时,它会返回错误消息。
// Java program to illustrate the
// Java.lang.Integer.reverseBytes() method
import 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