問題描述
我正在嘗試將十六進制字符串轉換為整數.字符串十六進制是從散列函數 (sha-1) 計算出來的.我收到此錯誤:java.lang.NumberFormatException.我猜它不喜歡十六進制的字符串表示.我怎樣才能做到這一點.這是我的代碼:
I am trying to convert a String hexadecimal to an integer. The string hexadecimal was calculated from a hash function (sha-1). I get this error : java.lang.NumberFormatException. I guess it doesn't like the String representation of the hexadecimal. How can I achieve that. Here is my code :
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();
}
例如,當我傳遞這個字符串時:_DTOWsHJbEeC6VuzWPawcLA,他的哈希值是:0xC934E5D372B2AB6D0A50B9F0341A00ED029BDC15
For example, when I pass this string : _DTOWsHJbEeC6VuzWPawcLA, his hash his : 0xC934E5D372B2AB6D0A50B9F0341A00ED029BDC15
但我得到:java.lang.NumberFormatException:對于輸入字符串:0xC934E5D372B2AB6D0A50B9F0341A00ED029BDC15"
But i get : java.lang.NumberFormatException: For input string: "0xC934E5D372B2AB6D0A50B9F0341A00ED029BDC15"
我真的需要這樣做.我有一組由它們的 UUID 標識的元素,它們是字符串.我將不得不存儲這些元素,但我的限制是使用整數作為它們的 id.這就是為什么我計算給定參數的哈希值,然后將其轉換為 int.也許我做錯了,但有人可以給我一個建議來正確地實現它!
I really need to do this. I have a collection of elements identified by their UUID which are string. I will have to store those elements but my restrictions is to use an integer as their id. It is why I calculate the hash of the parameter given and then I convert to an int. Maybe I am doing this wrong but can someone gives me an advice to achieve that correctly!!
感謝您的幫助!!
推薦答案
為什么不使用 java 功能呢:
Why do you not use the java functionality for that:
如果您的數字很小(比您的小),您可以使用:Integer.parseInt(hex, 16)
將十六進制 - 字符串轉換為整數.
If your numbers are small (smaller than yours) you could use: Integer.parseInt(hex, 16)
to convert a Hex - String into an integer.
String hex = "ff"
int value = Integer.parseInt(hex, 16);
對于像你這樣的大數字,使用 public BigInteger(String val, int radix)
For big numbers like yours, use public BigInteger(String val, int radix)
BigInteger value = new BigInteger(hex, 16);
@見JavaDoc:
- Integer.parseInt(String value, int radix)
- BigInteger(String value, int radix)
這篇關于Java中的十六進制轉整數的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!