2

I am trying to convert "0x6042607b1ba01d8dl" into a long.

I have tried:

long value = new BigInteger("0x6042607b1ba01d8dl", 16).longValue();
long value = new BigInteger("0x6042607b1ba01d8dl", 32).longValue();
long value = Long.decode("0x6042607b1ba01d8dl");
Long.parseLong("0x6042607b1ba01d8dl");

Note: The Hex number "0x6042607b1ba01d8dl" has 17 numbers

Alan Ford
  • 365
  • 1
  • 4
  • 15
  • 1
    possible duplicate of [How to convert a hexadecimal string to long in java?](http://stackoverflow.com/questions/5153811/how-to-convert-a-hexadecimal-string-to-long-in-java) – turbo May 21 '14 at 14:02
  • It would be quite helpful if you told us what happened as well, not just what you tried. – nos May 21 '14 at 14:19
  • "The Hex number ... has 17 numbers." Unless I'm mistaken, `6042 607b 1ba0 1d8d` has **16** digits so should fit in a 64b Java `long`. – Mike Samuel May 21 '14 at 14:23

4 Answers4

3

From the javadoc for the BigInteger(String,int) constructor:

The String representation consists of an optional minus or plus sign followed by a sequence of one or more digits in the specified radix.

So you just need to remove the 0x from your string:

long value = new BigInteger("6042607b1ba01d8d", 16).longValue();
Mike Samuel
  • 118,113
  • 30
  • 216
  • 245
Giovanni Botta
  • 9,626
  • 5
  • 51
  • 94
2

The BigInteger constructor does not understand your 0x prefix.

Use e.g.

long value = new BigInteger("6042607b1ba01d8d", 16).longValue();

Or:

String number = "0x6042607b1ba01d8d";
long value = new BigInteger(number.subString(2), 16).longValue();

You can also use Long.decode(), which does accept a 0x prefix for decoding hex.

nos
  • 223,662
  • 58
  • 417
  • 506
1

You can try this:

long value = Long.parseLong("6042607b1ba01d8d", 16);

Long.parseLong can sometimes fail for unsigned longs, so, the BigInteger approaches are better.

O. Jones
  • 103,626
  • 17
  • 118
  • 172
Pablo Arce
  • 91
  • 1
  • 8
0

As said by the above answers in code form:

String bigHexNumber = "0x6042607b1ba01d8d";
if(bigHexNumber.subString(0, 1).equals("0x") {
     bigHexNumber = bigHexNumber.subString(2);
}
long hexInLongForm = new BigInteger(bigHexNumber, 16).longValue();
DirkyJerky
  • 1,130
  • 5
  • 10