Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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. Then how can I convert it to a String or just print it in a 'unsigned' manner?

like image 789
Shawn Avatar asked Aug 13 '13 08:08

Shawn


People also ask

How do you convert primitive long to String?

One way to cast a long primitive type to String is by using String concatenation. The '+' operator in java is overloaded as a String concatenator. Anything added to a String object using the '+' operator becomes a String. In the above example, the output “4587” is a String type and is no longer a long.

Is there unsigned long in Java?

Although Java has no unsigned long type, you can treat signed 64-bit two's-complement integers (i.e. long values) as unsigned if you are careful about it. Many primitive integer operations are sign agnostic for two's-complement representations.


2 Answers

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);
}
like image 151
Peter Lawrey Avatar answered Sep 27 '22 22:09

Peter Lawrey


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
like image 26
Mifeet Avatar answered Sep 27 '22 22:09

Mifeet