有没有一种简单快速的方法将 Java 有符号长字符串转换为无符号长字符串?
-1 -> "18446744073709551615"
-9223372036854775808 -> "09223372036854775808"
9223372036854775807 -> "09223372036854775807"
0 -> "00000000000000000000"
这是使用 BigInteger 的解决方案:
/** the constant 2^64 */
private static final BigInteger TWO_64 = BigInteger.ONE.shiftLeft(64);
public String asUnsignedDecimalString(long l) {
BigInteger b = BigInteger.valueOf(l);
if(b.signum() < 0) {
b = b.add(TWO_64);
}
return b.toString();
}
This works since the unsigned value of a (signed) number in two-s complement is just 2(number of bits) more than the signed value, and Java's long
has 64 bits.
BigInteger 有这个很好的toString()
我们可以在这里使用的方法。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)