嗨我使用函数将十六进制字符串转换为字节数组,它给了我这个错误,有时它会有效地发生错误
引起:java.lang.StringIndexOutOfBoundsException:length = 7; index = 7> at java.lang.String.indexAndLength(String.java:500) 在java.lang.String.charAt(String.java:494)
public static byte[] hexStringToByteArray(String s) {
int len = s.length();
byte[] data = new byte[len/2];
for(int i = 0; i < len; i+=2){
data[i/2] = (byte) ((Character.digit(s.charAt(i), 16) << 4) + Character.digit(s.charAt(i+1), 16));
}
return data;
}
错误来自此代码和 为什么它在大多数时间都有效,并且有时只会使应用程序强制关闭,任何人都可以解决这个问题,以便它可以始终工作
我使用上面的函数将crc32 checsum转换为bytearray
这是我用来获取crc32 checsum的函数
private String chesum() {
String fileName = "file.bin";
try {
CheckedInputStream cis = null;
try {
// Compute CRC32 checksum
cis = new CheckedInputStream(
new FileInputStream(fileName), new CRC32());
} catch (FileNotFoundException e) {
System.err.println("File not found.");
}
byte[] buf = new byte[128];
while(cis.read(buf) >= 0) {
}
long checksum = cis.getChecksum().getValue();
String ss = Long.toHexString(checksum);
cis.close();
return ss;
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
在这个方法之后我调用hexstringtobytearray函数
答案 0 :(得分:1)
for(int i = 0; i < len-1 ; i+=2){
data[i/2] = (byte) ((Character.digit(s.charAt(i), 16) << 4) + Character.digit(s.charAt(i+1), 16));
}
将条件len
更改为len -1