ModBus CRC16計(jì)算

先貼資料 :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)
    }
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

友情鏈接更多精彩內(nèi)容