byte array to Hex (in int format)

861 views Asked by At

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)
2

There are 2 answers

0
SMA On BEST ANSWER

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);
0
Eran On

"202e4724bb138c1c60470adb623ac932" is too large to fit in an int or long. It would require 16 bytes (if I counted right).