Java.math.BigInteger.toByteArray() 方法
描述
java.math.BigInteger.toByteArray() 返回一个字节数组,其中包含此 BigInteger 的二进制补码表示。 字节数组将采用大端字节序:最高有效字节在第零个元素中。
该数组将包含表示此 BigInteger 所需的最小字节数,包括至少一个符号位,即 (ceil((this.bitLength() + 1)/8))。 此表示与 (byte[]) 构造函数兼容。
声明
以下是 java.math.BigInteger.toByteArray() 方法的声明。
public byte[] toByteArray()
参数
NA
返回值
此方法返回一个字节数组,其中包含此 BigInteger 的二进制补码表示。
异常
NA
示例
下面的例子展示了 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

