Convert C CRC16 to Java CRC16[android jni java C]-crc16校验

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[android jni java C]-crc16校验)