Alex W
Alex W

Reputation: 38193

Converting Signed Int to Unsigned String value in Java

To keep this short, I am getting a signed number, -25771 (in Java), that I need the unsigned String representation of, which is "4294941525". Java thinks the number is signed two's complement, but I need its unsigned value.

I noticed the Javadoc for the toString() method for Integers only converts to signed representation.

Is there not a bitwise operation such as "& 0xFF" that I can do to get the unsigned number?

Upvotes: 2

Views: 10944

Answers (3)

Hans Brende
Hans Brende

Reputation: 8537

In Java 8, you can just use Integer.toUnsignedString(int i).

Upvotes: 9

MikeFHay
MikeFHay

Reputation: 9013

You can use Guava's UnsignedInts.toString, and parseUnsignedInt to reverse the process.

Upvotes: 1

Peter Lawrey
Peter Lawrey

Reputation: 533500

I would try

int val = -25771;
System.out.println(Long.toString(val & 0xFFFFFFFFL));

prints

4294941525

or

"" + (val & 0xFFFFFFFFL)

Upvotes: 8

Related Questions