Search code examples
javahexarraystype-conversionnumberformatexception

byte array to Hex (in int format)


I have the following function to convert byte array to Hex in integer format.

private static int byteArray2Int(final byte[] hash) {
        Formatter formatter = new Formatter();
        for (byte b : hash) {
            formatter.format("%02x", b);
        }

        String str = formatter.toString();
        int hex = Integer.parseInt(str, 16);   //number format exception

        return hex; 
    }

--

And I'm getting below error. I understand the formatter value is already in hex but I want to store in integer format.

How do I go about it, please?

Exception in thread "main" java.lang.NumberFormatException: For input string: "202e4724bb138c1c60470adb623ac932"
    at java.lang.NumberFormatException.forInputString(NumberFormatException.java:48)

Solution

  • Use BigInteger as below instead of trying to store it in an int as your String is too long to fit in for within int range.

    String hex = "202e4724bb138c1c60470adb623ac932";
    BigInteger bi = new BigInteger(hex, 16);
    System.out.println(bi);