先貼資料 :https://blog.csdn.net/qq_26043945/article/details/123566360
{
//1、引言
//(1).CRC寄存器初始值為 0xFFFF;即16個(gè)字節(jié)全為1。
//(2).CRC-16/ModBus的模型為:X16+x15+X2+1,由于16進(jìn)制數(shù)只能0~15位,所以舍去X1位,最后得出:0x8005H(1000 0000 0000
//0101 B)。
//(3).通過把 0x8005H的“高位”與“低位”進(jìn)行互換,得到最終的多項(xiàng)式:0xA001H(1010 0000 0000 0001 B)
private static final int POLY = 0xa001;
public static String getCrc(byte[] bytes) {
int crc = 0xFFFF;
for (byte b : bytes) {
crc ^= b & 0xFF;
for (int i = 0; i < 8; i++) {
if ((crc & 1) != 0) {
crc >>= 1;
crc ^= POLY;
} else {
crc >>= 1;
}
}
}
return Integer.toHexString(crc);
}
}
校驗(yàn)地址:http://www.ip33.com/crc.html
補(bǔ)一個(gè)kt的
private const val POLY = 0xa001
fun getBytesCrc(bytes: ByteArray): ByteArray {
var crc = 0xFFFF
for (b in bytes) {
crc = crc xor (b.toInt() and 0xFF)
for (i in 0..7) {
if ((crc and 1) != 0) {
crc = crc shr 1
crc = crc xor POLY
} else {
crc = crc shr 1
}
}
}
return intTo2ByteArray(crc)
}