当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


Java Integer 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



相关用法


注:本文由纯净天空筛选整理自ankita_chowrasia大神的英文原创作品 Integer reverseBytes() Method in Java。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。