I want to convert a hex string to long in java.
I have tried with general conversion.
String s = "4d0d08ada45f9dde1e99cad9";
long l = Long.valueOf(s).longValue();
System.out.println(l);
String ls = Long.toString(l);
But I am getting this error message:
java.lang.NumberFormatException: For input string: "4d0d08ada45f9dde1e99cad9"
Is there any way to convert String to long in java? Or am i trying which is not really possible!!
Thanks!
Use parseLong:
Long.decode(str)
accepts a variety of formats:But in your case that won't help, your String is beyond the scope of what long can hold. You need a
BigInteger
:Output:
For Comparison, here's
Long.MAX_VALUE
:For any value of someLong:
In other words, this will return the
long
you sent intoLong.toHexString()
for anylong
value, including negative numbers. It will also accept strings that are bigger than along
and silently return the lower 64 bits of the string as along
. You can just check the string length <= 16 (after trimming whitespace) if you need to be sure the input fits in along
.Long.parseLong(s, 16)
will only work up to"7fffffffffffffff"
. UseBigInteger
instead: