一、c语言
uint16_t crc_chk(uint8_t *data, uint8_t len)
{
uint8_t i;
uint16_t reg_crc = 0xffff;
while(len--) {
reg_crc ^= *data++;
for(i = 0; i < 8; i++) {
if(reg_crc & 0x01) {
reg_crc = (reg_crc >> 1) ^ 0xA001;
} else {
reg_crc = reg_crc >> 1;
}
}
}
return reg_crc;
}
二、java语言
public class TestDemo {
/**
* crc 校验代码
*
* @param bufData
* byte类型的数组数据
* @param bufLen
* byte类型的数组数据的长度
* @return 计算后的校验码
*/
public static String crc_chk(byte[] bufData, int bufLen) {
int reg_crc = 0xffff;
for (int i = 0; i < bufLen; i++) {
reg_crc ^= ((int) bufData[i] & 0xff);
for (int j = 0; j < 8; j++) {
if ((reg_crc & 0x01) != 0) {
reg_crc = (reg_crc >> 1) ^ 0xa001;
} else {
reg_crc = reg_crc >> 1;
}
}
}
return Integer.toHexString(reg_crc);
}
public static byte[] HexString2Bytes(String src) {
byte[] ret = new byte[src.length() / 2];
byte[] tmp = src.getBytes();
for (int i = 0; i < tmp.length / 2; i++) {
ret[i] = uniteBytes(tmp[i * 2], tmp[i * 2 + 1]);
}
return ret;
}
public static byte uniteBytes(byte src0, byte src1) {
byte _b0 = Byte.decode("0x" + new String(new byte[] { src0 })).byteValue();
_b0 = (byte) (_b0 << 4);
byte _b1 = Byte.decode("0x" + new String(new byte[] { src1 })).byteValue();
byte ret = (byte) (_b0 ^ _b1);
return ret;
}
public static void main(String[] args) {
String ss = "AB0B0701140267010501";
byte[] dd = HexString2Bytes(ss);
System.out.println(crc_chk(dd, dd.length));
}
}
————————————————
版权声明:本文为CSDN博主「专注写bug」的原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/qq_38322527/article/details/89881758