[英]Hexadecimal to Integer in Java
我正在嘗試將十六進制字符串轉換為 integer。 字符串十六進制是根據 hash function (sha-1) 計算得出的。 我收到此錯誤:java.lang.NumberFormatException。 我猜它不喜歡十六進制的字符串表示。 我怎樣才能做到這一點。 這是我的代碼:
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 ,他的 hash 他的: 0xC934E5D372B2AB6D0A50B9F0341A00ED029BDC15
但我得到:java.lang.NumberFormatException:對於輸入字符串:“ 0xC934E5D372B2AB6D0A50B9F0341A00ED029BDC15 ”
我真的需要這樣做。 我有一組由它們的 UUID 標識的元素,它們是字符串。 我將不得不存儲這些元素,但我的限制是使用 integer 作為它們的 id。 這就是為什么我計算給定參數的 hash 然后轉換為 int 的原因。 也許我做錯了,但有人可以給我一個建議來正確地做到這一點!
謝謝你的幫助 !!
您為什么不為此使用 java 功能:
如果您的數字很小(小於您的數字),您可以使用: Integer.parseInt(hex, 16)
將十六進制字符串轉換為 integer。
String hex = "ff"
int value = Integer.parseInt(hex, 16);
對於像您這樣的大數字,請使用public BigInteger(String val, int radix)
BigInteger value = new BigInteger(hex, 16);
@見JavaDoc:
嘗試這個
public static long Hextonumber(String hexval)
{
hexval="0x"+hexval;
// String decimal="0x00000bb9";
Long number = Long.decode(hexval);
//....... System.out.println("String [" + hexval + "] = " + number);
return number;
//3001
}
您可以使用此方法: https://stackoverflow.com/a/31804061/3343174它可以完美地將任何十六進制數(以字符串形式)轉換為十進制數
SHA-1 生成 160 位消息(20 字節),太大而無法存儲在int
或long
值中。 正如 Ralph 建議的那樣,您可以使用 BigInteger。
要獲得(不太安全的)int hash,您可以返回返回字節數組的 hash 代碼。
或者,如果您根本不需要 SHA,您可以只使用 UUID 的字符串 hash 代碼。
我終於根據您的所有評論找到了我的問題的答案。 謝謝,我試過這個:
public Integer calculateHash(String uuid) {
try {
//....
String hex = hexToString(output);
//Integer i = Integer.valueOf(hex, 16).intValue();
//Instead of using Integer, I used BigInteger and I returned the int value.
BigInteger bi = new BigInteger(hex, 16);
return bi.intValue();`
} catch (NoSuchAlgorithmException e) {
System.out.println("SHA1 not implemented in this system");
}
//....
}
這個解決方案不是最優的,但我可以繼續我的項目。 再次感謝你的幫助
那是因為byte[] output
很好,而且是字節數組,你可能會認為它是一個字節數組,每個字節代表一個 integer,但是當你將它們全部添加到一個字符串中時,你得到的不是 Z152518ZDF536CCB63這就是為什么。 您可以將其作為整數數組,也可以嘗試創建BigInteger的實例。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.