Java - 将 20 字节的值转换为以 10 为基数的数字
Java - Converting 20 bytes value to base-10 number
我有一个关于 Java 中字节到 int/long 转换的查询。
有:
- 4 字节整数
- 8 字节长。
如何存储超过 8 个字节的值
以及 Java 将如何表示(例如:8 + 内存中的字节值)?
BigInteger is designed for this. Internally, it represents numbers with a (variable-length) vector that can be seen as a polynomial. It allows arbitrary-sized integers to be manipulated efficiently, as long as there is enough free memory to do so. Other languages have similar constructs or libraries; for instance, the GMP 库遵循类似的方法。
请注意,虽然 BigInteger
s 可以从 byte[]
二进制补码构建,并且可以再次转换为那些 byte[]
s,但在内部它们使用更高效的 int[]
表示。如有疑问,read the source.
示例代码如下:
import java.math.*;
public class T {
public static void main(String[] args) {
for (String s: args) {
// build from base-16 string representation
BigInteger bi = new BigInteger(s, 16);
System.out.println("The decimal representation of \n\t"
+ s + " is \n\t" + bi);
// (bi.toString() generates base-10 strings)
}
}
}
现在编译 & 运行:
javac T.java && java T 8df0c57980d7fa44e3a7286cfd9a4589c5eb1eb0
预期输出:
The decimal representation of
8df0c57980d7fa44e3a7286cfd9a4589c5eb1eb0 is
810337079999566280018410685437385308775358602928
我有一个关于 Java 中字节到 int/long 转换的查询。
有:
- 4 字节整数
- 8 字节长。
如何存储超过 8 个字节的值 以及 Java 将如何表示(例如:8 + 内存中的字节值)?
BigInteger is designed for this. Internally, it represents numbers with a (variable-length) vector that can be seen as a polynomial. It allows arbitrary-sized integers to be manipulated efficiently, as long as there is enough free memory to do so. Other languages have similar constructs or libraries; for instance, the GMP 库遵循类似的方法。
请注意,虽然 BigInteger
s 可以从 byte[]
二进制补码构建,并且可以再次转换为那些 byte[]
s,但在内部它们使用更高效的 int[]
表示。如有疑问,read the source.
示例代码如下:
import java.math.*;
public class T {
public static void main(String[] args) {
for (String s: args) {
// build from base-16 string representation
BigInteger bi = new BigInteger(s, 16);
System.out.println("The decimal representation of \n\t"
+ s + " is \n\t" + bi);
// (bi.toString() generates base-10 strings)
}
}
}
现在编译 & 运行:
javac T.java && java T 8df0c57980d7fa44e3a7286cfd9a4589c5eb1eb0
预期输出:
The decimal representation of
8df0c57980d7fa44e3a7286cfd9a4589c5eb1eb0 is
810337079999566280018410685437385308775358602928