如果我有一个 Java long
值 - 比如 x
- 它应该被解释为一个无符号值(即 0x8000_0000_0000_0000
和更高应该是解释为正值)那么如何将其转换为 BigInteger
?
显然,BigInteger.valueOf(x)
会产生负值,转换为十六进制或字节似乎很浪费。
最佳答案
实际上,转换非常简单。您可以使用类似于将无符号整数转换为长整数的掩码:
让我们首先将掩码创建为常量(这只会导致最低有效的 32 位设置为 1):
private static final long UNSIGNED_INT_MASK = (1L << Integer.SIZE) - 1L;
然后我们可以执行:
int unsignedInt = 0x8000_0000; // sample input value
long l = (long) unsignedInt & UNSIGNED_INT_MASK;
所以对于 BigInteger
,我们可以像这样创建掩码(64 个最低有效位设置为 1):
// use "import static java.math.BigInteger.ONE;" to shorten this line
private static final BigInteger UNSIGNED_LONG_MASK = BigInteger.ONE.shiftLeft(Long.SIZE).subtract(BigInteger.ONE);
很好,接下来就很简单了:
long unsignedLong = 0x8000_0000_0000_0000L; // sample input value
BigInteger bi = BigInteger.valueOf(unsignedLong).and(UNSIGNED_LONG_MASK);
这不是火箭科学,但有时您只想找到一个快速简单的答案。
关于java - 如何将 "unsigned"long 转换为 BigInteger,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55752927/