我正在尝试将用户的输入作为一个字符串,将该字符串分成两半并将这些字符串转换为十六进制整数。我需要在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:对于输入字符串:“ 6a54657874”
我已经在网上四处寻找这个问题,但错误表明当我将字符串转换为v [x]时发生了这种情况,多个站点说这是将十六进制字符串放入int的正确方法,因此我感到困惑。请帮忙。
最佳答案
6a54657874
,因为十六进制为456682469492
(十进制)。这比Integer.MAX_VALUE
大。它将适合long
。
将v
设置为long[]
并使用Long.parseLong(test, 16);