10

it is clear that java does not have 'unsigned long' type, while we can use long to store a unsigned data. Then how can I convert it to a String or just print it in a 'unsigned' manner?

Shawn
  • 1,351
  • 4
  • 19
  • 33

4 Answers4

13

You need to use BigInteger unfortunately, or write your own routine.

Here is an Unsigned class which 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);
}
Peter Lawrey
  • 498,481
  • 72
  • 700
  • 1,075
10

As mentioned in a different question on SO, there is a method for that starting with Java 8:

System.out.println(Long.toUnsignedString(Long.MAX_VALUE)); // 9223372036854775807
System.out.println(Long.toUnsignedString(Long.MIN_VALUE)); // 9223372036854775808
Community
  • 1
  • 1
Mifeet
  • 10,908
  • 3
  • 50
  • 92
4

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

Louis Wasserman
  • 172,699
  • 23
  • 307
  • 375
0
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;
Enyby
  • 3,484
  • 2
  • 26
  • 35
  • This is actually the same algorithm used by Java 8's [`Long.toUnsignedString()`](https://docs.oracle.com/en/java/javase/12/docs/api/java.base/java/lang/Long.html#toUnsignedString(long)). – Feuermurmel Feb 25 '20 at 11:16