How to Convert a Hexadecimal String to Long in Java

How to convert a hexadecimal string to long in java?

Long.decode(str) accepts a variety of formats:

Accepts decimal, hexadecimal, and octal
numbers given by the following
grammar:

DecodableString:

  • Signopt DecimalNumeral
  • Signopt 0x HexDigits
  • Signopt 0X HexDigits
  • Signopt # HexDigits
  • Signopt 0 OctalDigits

Sign:

  • -

But in your case that won't help, your String is beyond the scope of what long can hold. You need a BigInteger:

String s = "4d0d08ada45f9dde1e99cad9";
BigInteger bi = new BigInteger(s, 16);
System.out.println(bi);

Output:

23846102773961507302322850521

For Comparison, here's Long.MAX_VALUE:

9223372036854775807

NumberFormatException while converting Hexadecimal String to Long

In Java8, Long.parseUnsignedLong (javadoc) will handle this.

System.out.println(Long.parseUnsignedLong("cc10000000008401",16));

produces

-3742491290344848383

Convert hex string to int

It's simply too big for an int (which is 4 bytes and signed).

Use

Long.parseLong("AA0F245C", 16);

Convert a string representation of a hex dump to a byte array using Java?

Update (2021) - Java 17 now includes java.util.HexFormat (only took 25 years):

HexFormat.of().parseHex(s)


For older versions of Java:

Here's a solution that I think is better than any posted so far:

/* s must be an even-length string. */
public static byte[] hexStringToByteArray(String s) {
int len = s.length();
byte[] data = new byte[len / 2];
for (int i = 0; i < len; i += 2) {
data[i / 2] = (byte) ((Character.digit(s.charAt(i), 16) << 4)
+ Character.digit(s.charAt(i+1), 16));
}
return data;
}

Reasons why it is an improvement:

  • Safe with leading zeros (unlike BigInteger) and with negative byte values (unlike Byte.parseByte)

  • Doesn't convert the String into a char[], or create StringBuilder and String objects for every single byte.

  • No library dependencies that may not be available

Feel free to add argument checking via assert or exceptions if the argument is not known to be safe.

Converting a hex String to an int in Java

Your code seems incomplete, but based on your exception message, the input for Long.parseLong should be "E0030000" and NOT "0xE0030000".

public static void main(String[] args){
String hex="E0030000";
Long decimal=Long.parseLong(hex,16);
System.out.println(decimal);
}

output: 3758292992

Java - parse and unsigned hex string into a signed long

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

Convert hex string to long

Here's a short example of how you would do it using NSScanner:

NSString* pString = @"0xDEADBABE";
NSScanner* pScanner = [NSScanner scannerWithString: pString];

unsigned int iValue;
[pScanner scanHexInt: &iValue];


Related Topics



Leave a reply



Submit