【问题标题】:byte array to Hex (in int format)字节数组到十六进制( int 格式)
【发布时间】:2015-01-13 11:52:07
【问题描述】:

我有以下函数将字节数组转换为整数格式的十六进制。

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)

【问题讨论】:

  • 202e4724bb138c1c60470adb623ac932 不是 int,这就是您收到此异常的原因。

标签: java hex bytearray type-conversion numberformatexception


【解决方案1】:

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

【讨论】:

    【解决方案2】:

    如下所示使用 BigInteger 而不是尝试将其存储在 int 中,因为您的 String 太长而无法容纳在 int 范围内。

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

    【讨论】:

      猜你喜欢
      • 2015-08-08
      • 2018-02-28
      • 1970-01-01
      • 1970-01-01
      • 2017-09-13
      • 1970-01-01
      • 2013-08-09
      • 2013-10-13
      相关资源
      最近更新 更多