字节数组为十六进制(int格式)

时间:2014-11-16 14:21:38

标签: java hex bytearray type-conversion numberformatexception

我有以下函数将字节数组转换为整数格式的Hex。

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

-

我得到了以下错误。我理解格式化程序的值已经是十六进制,但我想以整数格式存储。

我该怎么办呢?

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

2 个答案:

答案 0 :(得分:1)

使用BigInteger,而不是尝试将其存储在int中,因为您的String太长而无法适应int范围。

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

答案 1 :(得分:0)

“202e4724bb138c1c60470adb623ac932”太大而无法放入int或long。它需要16个字节(如果我算得正确)。