从概念上讲,BigInteger 将整数转换为任意长度的位串,然后将位串拆分为 4 个字节。然后,将每个 4bytes 的结果分配给mag 数组中的每个元素:
BigInteger bi = new BigInteger("1234567890");
byte[] bytes = bi.toByteArray();
String rs = "";
for (byte b : bytes) {
String bs1 = Integer.toBinaryString(b & 0xff);
String bs2 = String.format("%8s", bs1).replace(' ', '0');
rs = rs + bs2 + " ";
}
System.out.println(bi.signum()); // 1
System.out.println(bi.bitLength()); // 31
System.out.println(rs); // 01001001 10010110 00000010 11010010
-
final int signum 是1 (00000000 00000000 00000000 00000001)。
-
final int[] mag 中的mag[0] 是1234567890 (01001001 10010110 00000010 11010010)。是的,mag 只有一个元素。
让我们表示更大的整数:
BigInteger bi = new BigInteger("12345678901234567890");
byte[] bytes = bi.toByteArray();
String rs = "";
for (byte b : bytes) {
String bs1 = Integer.toBinaryString(b & 0xff);
String bs2 = String.format("%8s", bs1).replace(' ', '0');
rs = rs + bs2 + " ";
}
System.out.println(bi.signum()); // 1
System.out.println(bi.bitLength()); // 64
System.out.println(rs); // 00000000 10101011 01010100 10101001 10001100 11101011 00011111 00001010 11010010
-
final int signum 是1 (00000000 00000000 00000000 00000001)。
-
final int[] mag 中的mag[0] 是-1420514932 (10101011 01010100 10101001 10001100)。
-
final int[] mag 中的mag[1] 是-350287150 (11101011 00011111 00001010 11010010)。
当我们用负整数实例化BigInteger 实例时:
BigInteger bi = new BigInteger("-1234567890");
byte[] bytes = bi.toByteArray();
String rs = "";
for (byte b : bytes) {
String bs1 = Integer.toBinaryString(b & 0xff);
String bs2 = String.format("%8s", bs1).replace(' ', '0');
rs = rs + bs2 + " ";
}
System.out.println(bi.signum()); // -1
System.out.println(bi.bitLength()); // 31
System.out.println(rs); // 10110110 01101001 11111101 00101110
-
final int signum 是-1 (11111111 11111111 11111111 11111111)。
-
final int[] mag 中的mag[0] 是1234567890 (01001001 10010110 00000010 11010010)。是的,mag 存储号码的大小。
- 当我们调用
toByteArray() 时,BigInteger 将mag 数组的幅度表示转换为2 的补码表示,因为signum 是-1,表示负值。所以,不要将toByteArray 视为BigInteger 的内部表示。
当我们用零实例化一个BigInteger 实例时:
BigInteger bi = new BigInteger("0");
byte[] bytes = bi.toByteArray();
String rs = "";
for (byte b : bytes) {
String bs1 = Integer.toBinaryString(b & 0xff);
String bs2 = String.format("%8s", bs1).replace(' ', '0');
rs = rs + bs2 + " ";
}
System.out.println(bi.signum()); // 0
System.out.println(bi.bitLength()); // 0
System.out.println(rs); // 00000000
-
final int signum 是0 (00000000 00000000 00000000 00000000)。
-
final int[] mag 没有元素;零大小的数组。 The magnitude must be "minimal" in that the most-significant int (mag[0]) must be non-zero. This is necessary to ensure that there is exactly one representation for each BigInteger value. Note that this implies that the BigInteger zero has a zero-length mag