user23
user23

Reputation: 425

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)

Upvotes: 0

Views: 897

Answers (2)

SMA
SMA

Reputation: 37023

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

Upvotes: 1

Eran
Eran

Reputation: 393801

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

Upvotes: 0

Related Questions