简体   繁体   中英

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)

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM