我试图将用户的输入作为字符串接收,将该字符串分成两半并将这些字符串转换为十六进制整数。我需要在 TEA 加密算法中使用这些十六进制整数。我正在 netbeans 中为 gui 构建器编写此代码。
我当前的代码
//Getting initial text
String arg = input.getText();
//establishing Left and Right for TEA
int[] v = new int[2];
// Splitting the string into two.
StringBuilder output2;
for (int x = 0; x < 2; x++ ) {
output2 = new StringBuilder();
for (int i = 0; i < arg.length()/2; i++) {
if (x == 1)
output2.append(String.valueOf(arg.charAt(arg.length()/2 + i)));
else
output2.append(String.valueOf(arg.charAt(i)));
}
//converting a half into a string
String test = output2.toString();
//printing the string out for accuracy
System.out.println(test);
//converting the string to string hex
test = toHex(test);
//converting the string hex to int hex.
v[x] = Integer.parseInt(test, 16);
}
public static String toHex(String arg) {
return String.format("%x", new BigInteger(arg.getBytes()));
}
我收到此错误:
java.lang.NumberFormatException: For input string: "6a54657874"
我在网上查找了这个问题,但错误表明当我将字符串转换为 v[x] 时会发生这种情况,多个网站都说这是将十六进制字符串放入 int 的正确方法,所以我很困惑。请帮忙。
最佳答案
6a54657874
十六进制是 456682469492
十进制。这比 Integer.MAX_VALUE
大。它将适合long
。
将 v
设为 long[]
并使用 Long.parseLong(test, 16);
关于java - Java中的十六进制转换错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16124728/