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?
Asked
Active
Viewed 5,559 times
10
-
what do you mean "print it in a unsigned manner" ? – erencan Aug 13 '13 at 08:40
4 Answers
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);
}
![](../../users/profiles/57695.webp)
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
4
Can you use third-party libraries? Guava's UnsignedLongs.toString(long)
does this.
![](../../users/profiles/869736.webp)
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;
![](../../users/profiles/1504248.webp)
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