Java中的十六进制到整数

Dim*_*tri 29 java hex integer

我试图将String十六进制转换为整数.字符串十六进制是从散列函数(sha-1)计算的.我收到此错误:java.lang.NumberFormatException.我猜它不喜欢十六进制的String表示.我怎样才能做到这一点.这是我的代码:

public Integer calculateHash(String uuid) {

    try {
        MessageDigest digest = MessageDigest.getInstance("SHA1");
        digest.update(uuid.getBytes());
        byte[] output = digest.digest();

        String hex = hexToString(output);
        Integer i = Integer.parseInt(hex,16);
        return i;           

    } catch (NoSuchAlgorithmException e) {
        System.out.println("SHA1 not implemented in this system");
    }

    return null;
}   

private String hexToString(byte[] output) {
    char hexDigit[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
            'A', 'B', 'C', 'D', 'E', 'F' };
    StringBuffer buf = new StringBuffer();
    for (int j = 0; j < output.length; j++) {
        buf.append(hexDigit[(output[j] >> 4) & 0x0f]);
        buf.append(hexDigit[output[j] & 0x0f]);
    }
    return buf.toString();

}
Run Code Online (Sandbox Code Playgroud)

例如,当我传递这个字符串:_DTOWsHJbEeC6VuzWPawcLA时,他的哈希值为:0xC934E5D372B2AB6D0A50B9F0341A00ED029BDC15

但我得到:java.lang.NumberFormatException:对于输入字符串:" 0xC934E5D372B2AB6D0A50B9F0341A00ED029BDC15 "

我真的需要这样做.我有一个由UUID标识的元素集合,它们是字符串.我将不得不存储这些元素,但我的限制是使用整数作为他们的id.这就是我计算给定参数的哈希然后转换为int的原因.也许我做错了,但有人可以给我一个建议来正确实现!

谢谢你的帮助 !!

Ral*_*lph 88

为什么不使用java功能:

如果您的数字很小(小于您的数字),您可以使用: Integer.parseInt(hex, 16)将Hex - String转换为整数.

  String hex = "ff"
  int value = Integer.parseInt(hex, 16);  
Run Code Online (Sandbox Code Playgroud)

对于像你这样的大数字,请使用 public BigInteger(String val, int radix)

  BigInteger value = new BigInteger(hex, 16);
Run Code Online (Sandbox Code Playgroud)

@See JavaDoc: