Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert a hexadecimal string to long in java?

People also ask

Can we 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 long is hex String?

HEX(x,z) returns a character string that contains x with the character z inserted between every set of eight characters in the output string. Its length is 2 * size(x) + ((size(x) - 1)/4) .

How do you convert hex to bytes?

To convert hex string to byte array, you need to first get the length of the given string and include it while creating a new byte array. byte[] val = new byte[str. length() / 2]; Now, take a for loop until the length of the byte array.

How does Java handle hexadecimal?

In Java code (as in many programming languages), hexadecimal nubmers are written by placing 0x before them. For example, 0x100 means 'the hexadecimal number 100' (=256 in decimal). Decimal values of hexadecimal digits.


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


Use parseLong:

Long.parseLong(s, 16)

new BigInteger(string, 16).longValue()

For any value of someLong:

new BigInteger(Long.toHexString(someLong), 16).longValue() == someLong

In other words, this will return the long you sent into Long.toHexString() for any long value, including negative numbers. It will also accept strings that are bigger than a long and silently return the lower 64 bits of the string as a long. You can just check the string length <= 16 (after trimming whitespace) if you need to be sure the input fits in a long.


Long.parseLong(s, 16) will only work up to "7fffffffffffffff". Use BigInteger instead:

public static boolean isHex(String hex) {
    try {
        new BigInteger(hex, 16);
        return true;
    } catch (NumberFormatException e) {
        return false;
    }
}