Java.math.BigInteger.toByteArray() 方法



說明

java.math.BigInteger.toByteArray() 返回一個包含這個 BigInteger 的二進位制補碼錶示形式的位元組陣列。這個位元組陣列將處於大端位元組順序:最高有效位位於第 0 個元素中。

此陣列將包含表示這個 BigInteger 所需的最小位元組數,包括至少一個符號位,即 (ceil((this.bitLength() + 1)/8))。此表示形式與 (byte[ ]) 建構函式相容。

宣告

以下是 java.math.BigInteger.toByteArray() 方法的宣告。

public byte[] toByteArray()

引數

不適用

返回值

此方法返回一個包含這個 BigInteger 的二進位制補碼錶示形式的位元組陣列。

異常

不適用

示例

以下示例顯示了 math.BigInteger.toByteArray() 方法的用法。

package com.tutorialspoint;

import java.math.*;

public class BigIntegerDemo {

   public static void main(String[] args) {

      // create 2 BigInteger objects
      BigInteger bi1, bi2;

      // create 2 byte arrays
      byte b1[], b2[];

      // create and assign value to byte array b3
      byte b3[] = { 0x1, 0x00, 0x00 };

      bi1 = new BigInteger("10");
      bi2 = new BigInteger(b3); // using byte[] constructor of BigInteger

      // assign byte array representation of bi1, bi2 to b1, b2
      b1 = bi1.toByteArray();
      b2 = bi2.toByteArray();

      String str1 = "Byte array representation of " + bi1 + " is: ";

      System.out.println( str1 );

      // print byte array b1 using for loop
      for (int i = 0; i  < b1.length; i++) {
         System.out.format("0x%02X\n", b1[i]);
      }

      String str2 = "Byte array representation of " + bi2 + " is: ";

      System.out.println( str2 );

      // print byte array b2 using for loop
      for (int j = 0; j < b2.length; j++) {
         System.out.format("0x%02X ", b2[j]);
      }
   }
}

讓我們編譯並執行以上程式,它將產生以下結果 -

Byte array representation of 10 is:
0x0A
Byte array representation of 65536 is:
0x01 0x00 0x00
java_math_biginteger.htm
廣告
© . All rights reserved.