How to convert 'unsigned long' to string in java

it is clear that java is not of type unsigned long, while we can use long to store unsigned data. Then how can I convert it to String or just print it unsigned?

+7
java long-integer
source share
3 answers

Unfortunately, you need to use BigInteger or write your own procedure.

Here is an unsigned class that helps with these workarounds

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); } 
+12
source share

As mentioned in another question on SO, there is a method for doing this starting with Java 8:

 System.out.println(Long.toUnsignedString(Long.MAX_VALUE)); // 9223372036854775807 System.out.println(Long.toUnsignedString(Long.MIN_VALUE)); // 9223372036854775808 
+4
source share

Can you use third-party libraries? Guava UnsignedLongs.toString(long) does this.

+3
source share

All Articles