有没有一种简单快捷的方法将Java签名长转换为无符号长字符串?
-1 -> "18446744073709551615"
-9223372036854775808 -> "09223372036854775808"
9223372036854775807 -> "09223372036854775807"
0 -> "00000000000000000000"
Run Code Online (Sandbox Code Playgroud)
Paŭ*_*ann 27
这是使用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();
}
Run Code Online (Sandbox Code Playgroud)
这是有效的,因为二进制补码中的(带符号)数的无符号值比有符号值多2 (比特数),而Java long有64比特.
BigInteger有这个很好的toString()方法,我们可以在这里使用.
Java 8包含对unsigned longs的一些支持.如果您不需要零填充,只需执行以下操作:
Long.toUnsignedString(n);
Run Code Online (Sandbox Code Playgroud)
如果您需要零填充,格式化不适用于无符号长整数.但是,此解决方法使用无符号除以10将无符号值拖放到可以在长整数中没有符号位的情况下表示的值:
String.format("%019d%d", Long.divideUnsigned(n, 10), Long.remainderUnsigned(n, 10));
Run Code Online (Sandbox Code Playgroud)
根据@PaŭloEbermann解决方案,我想出了这个:
public static String convert(long x) {
return new BigInteger(1, new byte[] { (byte) (x >> 56),
(byte) (x >> 48), (byte) (x >> 40), (byte) (x >> 32),
(byte) (x >> 24), (byte) (x >> 16), (byte) (x >> 8),
(byte) (x >> 0) }).toString();
}
Run Code Online (Sandbox Code Playgroud)
使用new BigInteger(int signum, byte[] bytes);BigInteger将字节读取为正数(无符号)并对其应用signum.
根据@Chris Jester-Young解决方案,我找到了这个:
private static DecimalFormat zero = new DecimalFormat("0000000000000000000");
public static String convert(long x) {
if (x >= 0) // this is positive
return "0" + zero.format(x);
// unsigned value + Long.MAX_VALUE + 1
x &= Long.MAX_VALUE;
long low = x % 10 + Long.MAX_VALUE % 10 + 1;
long high = x / 10 + Long.MAX_VALUE / 10 + low / 10;
return zero.format(high) + low % 10;
}
Run Code Online (Sandbox Code Playgroud)
还有另一种方法:
private static DecimalFormat zero19 = new DecimalFormat("0000000000000000000");
public static String convert(long x) {
if (x >= 0) {
return "0" + zero19.format(x);
} else if (x >= -8446744073709551616L) {
// if: x + 18446744073709551616 >= 10000000000000000000
// then: x + 18446744073709551616 = "1" + (x + 8446744073709551616)
return "1" + zero19.format(x + 8446744073709551616L);
} else {
// if: x + 18446744073709551616 < 10000000000000000000
// then: x + 18446744073709551616 = "09" + (x + 9446744073709551616)
// so: 9446744073709551616 == -9000000000000000000L
return "09" + (x - 9000000000000000000L);
}
}
Run Code Online (Sandbox Code Playgroud)