當前位置: 首頁>>代碼示例 >>用法及示例精選 >>正文


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。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。