我在使用十六进制值的 crc 计算器时遇到一些问题。 事实上,我有这个很好的代码,可以使用 ASCII 输入正确计算。
但是我需要计算“44007A0004 ...”的十六进制字符串无法转换为ASCII字符。如何更改函数来计算十六进制输入字符串 crc?
public String CRC_CCITT( int flag,String str) {
int crc = 0x00; // initial value
int polynomial = 0x1021;
byte[] bytes = str.getBytes();
switch(flag){
case 1:
crc=0x00;
break;
case 2:
crc=0xFFFF;
break;
case 3:
crc=0x1D0F;
break;
}
for (int index = 0 ; index< bytes.length; index++) {
byte b = bytes[index];
for (int i = 0; i < 8; i++) {
boolean bit = ((b >> (7-i) & 1) == 1);
boolean c15 = ((crc >> 15 & 1) == 1);
crc <<= 1;
if (c15 ^ bit) crc ^= polynomial;
}
}
crc &= 0xffff;
str = Integer.toHexString(crc);
return str;
}
最佳答案
引用这个答案:
Convert a string representation of a hex dump to a byte array using Java?
将 hexStringToByteArray
函数添加到您的代码中并按如下方式调用:
byte[] bytes = hexStringToByteArray(str);
关于java - Android Java CRC 十六进制输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30326440/