Convert C CRC16 to Java CRC16[an

作者: PengPengPro | 来源:发表于2017-03-02 10:47 被阅读208次

    The packets get a crc16 checksum at the end and it's calculated based on this algorithm:

    C

    uint16_t crc16 (const uint8_t * buffer, uint32_t size) {
        uint16_t crc = 0xFFFF;
    
        if (buffer && size)
            while (size--)
            {
                crc = (crc >> 8) | (crc << 8);
                crc ^= *buffer++;
                crc ^= ((unsigned char) crc) >> 4;
                crc ^= crc << 12;
                crc ^= (crc & 0xFF) << 5;
            }
    
        return crc;
    }
    

    java

    static int crc16(final byte[] buffer) {
        int crc = 0xFFFF;
    
        for (int j = 0; j < buffer.length ; j++) {
            crc = ((crc  >>> 8) | (crc  << 8) )& 0xffff;
            crc ^= (buffer[j] & 0xff);//byte to int, trunc sign
            crc ^= ((crc & 0xff) >> 4);
            crc ^= (crc << 12) & 0xffff;
            crc ^= ((crc & 0xFF) << 5) & 0xffff;
        }
        crc &= 0xffff;
        return crc;
    
    }
    

    相关文章

      网友评论

        本文标题:Convert C CRC16 to Java CRC16[an

        本文链接:https://www.haomeiwen.com/subject/wxyhgttx.html