【发布时间】:2015-07-10 06:51:46
【问题描述】:
嗨,我使用函数将十六进制字符串转换为字节数组,它有时会给我这个错误,有时它会工作,有时它会出错
原因: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 校验和到 bytearray
这是我用来获取 crc32 校验和的函数
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 函数
【问题讨论】:
-
我认为当长度为奇数时它会引发错误,因此请检查条件。