Is there an easy and fast way to convert a Java signed long to an unsigned long string?
-1 -> "18446744073709551615" -9223372036854775808 -> "09223372036854775808" 9223372036854775807 -> "09223372036854775807" 0 -> "00000000000000000000"
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.
The L suffix tells the compiler that we have a long number literal. Java byte , short , int and long types are used do represent fixed precision numbers. This means that they can represent a limited amount of integers. The largest integer number that a long type can represent is 9223372036854775807.
unsigned provides a few methods to convert a long value to an unsigned value. One of the methods is the valueOf() method that takes a long value. In the program, we create a BigInteger and then in the ULong. valueOf() method, we pass the long value using bigInteger.
Unsigned long variables are extended size variables for number storage, and store 32 bits (4 bytes). Unlike standard longs unsigned longs won't store negative numbers, making their range from 0 to 4,294,967,295 (2^32 - 1).
Here is a solution using BigInteger:
/** the constant 2^64 */ private static final BigInteger TWO_64 = BigInteger.ONE.shiftLeft(64); public String asUnsignedDecimalString(long l) { BigInteger b = BigInteger.valueOf(l); if(b.signum() < 0) { b = b.add(TWO_64); } return b.toString(); }
This works since the unsigned value of a (signed) number in two-s complement is just 2(number of bits) more than the signed value, and Java's long
has 64 bits.
And BigInteger has this nice toString()
method which we can use here.
Java 8 includes some support for unsigned longs. If you don't need the zero padding, just do:
Long.toUnsignedString(n);
If you need zero padding, formatting doesn't work for unsigned longs. However this workaround does an unsigned divide by 10 to drop the unsigned value to a point where it can be represented without the sign bit in the long:
String.format("%019d%d", Long.divideUnsigned(n, 10), Long.remainderUnsigned(n, 10));
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