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


Java Integer reverseBytes(int i)用法及代碼示例

Java Integer 類的 reverseBytes() 方法以數字方式返回通過反轉指定整數值的 2 的補碼二進製表示中的字節順序而獲得的值。

用法:

以下是 reverseBytes() 方法的聲明:

public static int reverseBytes(int i)

參數:

數據類型 參數 描述 必需/可選
int i 要反轉其字節的整數值。 Required

返回值:

reverseBytes() 方法返回通過顛倒指定 int 值中的字節順序獲得的數值。

異常:

NA

兼容版本:

Java 1.5 及以上

例子1

public class IntegerReverseBytesExample1 {
    public static void main(String[] args) {
          int i = 202;
          System.out.println("Number = " + i);
          //returns the value obtained by reversing order of the bytes in the specified int value
          System.out.println("After reversing = " + Integer.reverseBytes(i));
    }
}

輸出:

Number = 202
After reversing = -905969664

例子2

import java.util.Scanner;
public class IntegerReverseBytesExample2 {
    public static void main(String[] args) {
        System.out.print("Enter Integer Value:");
        Scanner readInput = new Scanner(System.in);
        int i = readInput.nextInt();
        readInput.close();
        System.out.println("Number = " + i);
        // returns the integer value in binary	         
        System.out.println("Binary Representation = " + Integer.toBinaryString(i));
        //returns the value obtained by reversing order of the bytes in the specified int value
        System.out.println("After reversing = " + Integer.reverseBytes(i));
    }
}

輸出:

Enter Integer Value:208
Number = 208
Binary Representation = 11010000
After reversing = -805306368

例子3

public class IntegerReverseBytesExample3 {
    public static void main(String[] args) {
          int a = 202;
          int b = -50;
          System.out.println("Number = " + a);	         
          System.out.println("Binary Representation = " + Integer.toBinaryString(a));	      
          System.out.println("After reversing = " + Integer.reverseBytes(a));
          System.out.println("\nNumber = " + b);	         
          System.out.println("Binary Representation = " + Integer.toBinaryString(b));	      
          System.out.println("After reversing = " + Integer.reverseBytes(b));
    }
}

輸出:

Number = 202
Binary Representation = 11001010
After reversing = -905969664

Number = -50
Binary Representation = 11111111111111111111111111001110
After reversing = -822083585

示例 4

import java.util.Scanner;
public class LongReverseBytesExample4 {
    public static void main(String[] args) {
        System.out.print("Enter Number from console:");
        Scanner sc = new Scanner(System.in);
        // assign the input to a variable
        long value = sc.nextLong();
        // get the value by reversing the order of the bytes 
        long result = Long.reverseBytes(value);
        // print the result
        System.out.println("Result:" + result);
        sc.close();
    }
}

輸出:

Enter Number from console:850
Result:5909567136040222720






相關用法


注:本文由純淨天空篩選整理自 Java Integer reverseBytes (int i) Method。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。