如何将“unsigned”long转换为BigInteger

问题描述 投票:2回答:1

如果我有一个Java long值 - 比如x - 应该被解释为无符号值(即0x8000_0000_0000_0000和更高应该被解释为正值)那么我怎样才能将它转换为BigInteger

显然,BigInteger.valueOf(x)会产生负值,转换为十六进制或字节似乎是浪费。

java long-integer biginteger
1个回答
5
投票

实际上,转换非常简单。您可以使用类似于将无符号整数转换为long的掩码:


让我们首先将掩码创建为常量(这只会导致最低有效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);

这不是火箭科学,但有时你只想找到一个快速简单的答案。

© www.soinside.com 2019 - 2024. All rights reserved.