Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java: signed long to unsigned long string

Tags:

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" 
like image 373
Ali Shakiba Avatar asked Aug 11 '11 18:08

Ali Shakiba


People also ask

Is Long signed or unsigned 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.

Does Java have longlong?

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.

How do you make a long unsigned?

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.

Can long be unsigned?

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).


2 Answers

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.

like image 56
Paŭlo Ebermann Avatar answered Sep 23 '22 07:09

Paŭlo Ebermann


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)); 
like image 22
lreeder Avatar answered Sep 22 '22 07:09

lreeder