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,441
  • 4
  • 22
  • 36

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
  • 525,659
  • 79
  • 751
  • 1,130
11

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
  • 12,949
  • 5
  • 60
  • 108
4

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

Louis Wasserman
  • 191,574
  • 25
  • 345
  • 413
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
  • 4,162
  • 2
  • 33
  • 42
  • 1
    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