[java] Hexadecimal to Integer in Java

I am trying to convert a String hexadecimal to an integer. The string hexadecimal was calculated from a hash function (sha-1). I get this error : java.lang.NumberFormatException. I guess it doesn't like the String representation of the hexadecimal. How can I achieve that. Here is my code :

public Integer calculateHash(String uuid) {

    try {
        MessageDigest digest = MessageDigest.getInstance("SHA1");
        digest.update(uuid.getBytes());
        byte[] output = digest.digest();

        String hex = hexToString(output);
        Integer i = Integer.parseInt(hex,16);
        return i;           

    } catch (NoSuchAlgorithmException e) {
        System.out.println("SHA1 not implemented in this system");
    }

    return null;
}   

private String hexToString(byte[] output) {
    char hexDigit[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
            'A', 'B', 'C', 'D', 'E', 'F' };
    StringBuffer buf = new StringBuffer();
    for (int j = 0; j < output.length; j++) {
        buf.append(hexDigit[(output[j] >> 4) & 0x0f]);
        buf.append(hexDigit[output[j] & 0x0f]);
    }
    return buf.toString();

}

For example, when I pass this string : _DTOWsHJbEeC6VuzWPawcLA, his hash his : 0xC934E5D372B2AB6D0A50B9F0341A00ED029BDC15

But i get : java.lang.NumberFormatException: For input string: "0xC934E5D372B2AB6D0A50B9F0341A00ED029BDC15"

I really need to do this. I have a collection of elements identified by their UUID which are string. I will have to store those elements but my restrictions is to use an integer as their id. It is why I calculate the hash of the parameter given and then I convert to an int. Maybe I am doing this wrong but can someone gives me an advice to achieve that correctly!!

Thanks for your help !!

This question is related to java integer hex

The answer is


Try this

public static long Hextonumber(String hexval)
    {
        hexval="0x"+hexval;
//      String decimal="0x00000bb9";
        Long number = Long.decode(hexval);
//.......       System.out.println("String [" + hexval + "] = " + number);
        return number;
        //3001
    }

SHA-1 produces a 160-bit message (20 bytes), too large to be stored in an int or long value. As Ralph suggests, you could use BigInteger.

To get a (less-secure) int hash, you could return the hash code of the returned byte array.

Alternatively, if you don't really need SHA at all, you could just use the UUID's String hash code.


That's because the byte[] output is well, and array of bytes, you may think on it as an array of bytes representing each one an integer, but when you add them all into a single string you get something that is NOT an integer, that's why. You may either have it as an array of integers or try to create an instance of BigInteger.


you can use this method : https://stackoverflow.com/a/31804061/3343174 it's converting perfectly any hexadecimal number (presented as a string) to a decimal number


I finally find answers to my question based on all of your comments. Thanks, I tried this :

public Integer calculateHash(String uuid) {

    try {
        //....
        String hex = hexToString(output);
        //Integer i = Integer.valueOf(hex, 16).intValue();
        //Instead of using Integer, I used BigInteger and I returned the int value.
        BigInteger bi = new BigInteger(hex, 16);
        return bi.intValue();`
    } catch (NoSuchAlgorithmException e) {
        System.out.println("SHA1 not implemented in this system");
    }
    //....
}

This solution is not optimal but I can continue with my project. Thanks again for your help


Examples related to java

Under what circumstances can I call findViewById with an Options Menu / Action Bar item? How much should a function trust another function How to implement a simple scenario the OO way Two constructors How do I get some variable from another class in Java? this in equals method How to split a string in two and store it in a field How to do perspective fixing? String index out of range: 4 My eclipse won't open, i download the bundle pack it keeps saying error log

Examples related to integer

Python: create dictionary using dict() with integer keys? How to convert datetime to integer in python Can someone explain how to append an element to an array in C programming? How to get the Power of some Integer in Swift language? python "TypeError: 'numpy.float64' object cannot be interpreted as an integer" What's the difference between integer class and numeric class in R PostgreSQL: ERROR: operator does not exist: integer = character varying C++ - how to find the length of an integer Converting binary to decimal integer output Convert floats to ints in Pandas?

Examples related to hex

Transparent ARGB hex value How to convert a hex string to hex number Javascript: Unicode string to hex Converting Hexadecimal String to Decimal Integer Convert string to hex-string in C# Print a variable in hexadecimal in Python Convert ascii char[] to hexadecimal char[] in C Hex transparency in colors printf() formatting for hex Python Hexadecimal