Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java - parse and unsigned hex string into a signed long

I have a bunch of hex strings, one of them, for example is:

  d1bc4f7154ac9edb

which is the hex value of "-3333702275990511909". This is the same hex you get if you do Long.toHexString("d1bc4f7154ac9edb");

For now, let's just assume I only have access to the hex string values and that is it. Doing this:

  Long.parseLong(hexstring, 16);

Doesn't work because it converts it to a different value that is too large for a Long. Is there away to convert these unsigned hex values into signed longs?

Thanks!

like image 849
Peter Avatar asked Apr 19 '11 22:04

Peter


2 Answers

You can use BigInteger to parse it and get back a long:

long value = new BigInteger("d1bc4f7154ac9edb", 16).longValue();
System.out.println(value); // this outputs -3333702275990511909
like image 169
WhiteFang34 Avatar answered Oct 11 '22 15:10

WhiteFang34


You may split it in half and read 32 bits at a time. Then use shift-left by 32 and a logical or to get it back into a single long.

like image 23
Knut Forkalsrud Avatar answered Oct 11 '22 15:10

Knut Forkalsrud