Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Parse Negative Long in Hex in Java

Tags:

java

hex

We have a J2ME application that needs to read hex numbers. The application is already too big for some phones so We try not to include any other codec or write our own function to do this.

All the numbers are 64-bit signed integers in hex, when we use Long.ParseLong(hex, 16), it handles positive numbers correctly but it throws exception on negative numbers,

    long l = Long.parseLong("FFFFFFFFFFFFFFFF", 16);

How can we get -1 from that hex string using classes provided in Java itself?

Some people may suggest we should write our hex as -1 as Java expected. Sorry, the format is fixed by the protocol and we can't change it.

like image 504
ZZ Coder Avatar asked Sep 11 '09 10:09

ZZ Coder


People also ask

Can a long be negative in Java?

Yes it does support negative values as long as it is not appended after unsigned .

How to convert String to long in Java?

There are many methods for converting a String to a Long data type in Java which are as follows: Using the parseLong() method of the Long class. Using valueOf() method of long class. Using constructor of Long class.

How to convert hexstring to Int in Java?

To convert a hexadecimal string to a number Use the ToInt32(String, Int32) method to convert the number expressed in base-16 to an integer.


2 Answers

Your problem is that parseLong() does not handle two's complement - it expects the sign to be present in the form of a '-'.

If you're developing for the CDC profile, you can simple use

long l = new BigInteger("FFFFFFFFFFFFFFFF", 16).longValue()

But the CLDC profile doesn't have that class. There, the easiest way to do what you need is probably to split up the long, parse it in two halves and recombine them. This works:

long msb = Long.parseLong("FFFFFFFF", 16);
long lsb = Long.parseLong("FFFFFFFF", 16);
long result = msb<<32 | lsb;

UPDATE

As of Java 8, you can use parseUnsignedLong():

long l = Long.parseUnsignedLong("FFFFFFFFFFFFFFFF", 16);
like image 78
Michael Borgwardt Avatar answered Oct 24 '22 01:10

Michael Borgwardt


Parse it in chunks.

    long l = (Long.parseLong("FFFFFFFFF",16)<<32) | Long.parseLong("FFFFFFFF",16);
like image 42
Billy Bob Bain Avatar answered Oct 24 '22 00:10

Billy Bob Bain