简体   繁体   English

如何在java中将'unsigned long'转换为字符串

[英]How to convert 'unsigned long' to string in java

it is clear that java does not have 'unsigned long' type, while we can use long to store a unsigned data. 很明显,java没有'unsigned long'类型,而我们可以使用long来存储无符号数据。 Then how can I convert it to a String or just print it in a 'unsigned' manner? 那么如何将其转换为String或只是以“无符号”方式打印?

You need to use BigInteger unfortunately, or write your own routine. 不幸的是,您需要使用BigInteger,或者编写自己的例程。

Here is an Unsigned class which helps with these workarounds 这是一个Unsigned类,它可以帮助解决这些问题

private static final BigInteger BI_2_64 = BigInteger.ONE.shiftLeft(64);

public static String asString(long l) {
    return l >= 0 ? String.valueOf(l) : toBigInteger(l).toString();
}

public static BigInteger toBigInteger(long l) {
    final BigInteger bi = BigInteger.valueOf(l);
    return l >= 0 ? bi : bi.add(BI_2_64);
}

As mentioned in a different question on SO, there is a method for that starting with Java 8: 正如在SO上的另一个问题中所提到的,从Java 8开始有一种方法:

System.out.println(Long.toUnsignedString(Long.MAX_VALUE)); // 9223372036854775807
System.out.println(Long.toUnsignedString(Long.MIN_VALUE)); // 9223372036854775808

Can you use third-party libraries? 你可以使用第三方库吗? Guava's UnsignedLongs.toString(long) does this. Guava的UnsignedLongs.toString(long)这样做的。

long quot = (number >>> 1) / 5L; // get all digits except last one
long rem = number - quot * 10L; // get last digit with overflow trick
String out = Long.toString(quot) + rem;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM