一、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