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?
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.
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.
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);
}
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With