[英]What is the easiest way to convert an unsigned long to BigInteger
Java 不支持無符號長整型,但如果您將長整型視為無符號並進行乘法,它就可以正常工作。 為了進行比較,您可以使用Long.compareUnsigned()
。
當我做
long v = Long.MAX_VALUE; //2^63
v = v+1;
BigInteger vv = BigInteger.valueOf(v);
System.out.println(vv);//this prints -1
我發現的唯一方法是做
long v = Long.MAX_VALUE; //2^63
v = v+1;
BigInteger vv = new BigInteger(Long.toUnsignedString(v));
System.out.println(vv);//this prints 2^63+1
使用您對 2 的補碼算法工作原理的了解,您可以執行以下操作:
private final BigInteger TWO_POW_64 = BigInteger.TWO.pow(64);
...
Long v = <some negative value to be treated as unsigned>;
BigInteger b = BigInteger.valueOf(v).mod(TWO_POW_64);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.