Convert C CRC16 to Java CRC16

前端 未结 1 735
失恋的感觉
失恋的感觉 2021-01-02 13:12

I am currently working on a project, having an embedded system sending data to a PC via radio. The packets get a crc16 checksum at the end and it\'s calculated based on this

相关标签:
1条回答
  • 2021-01-02 13:30

    The major difference between java and c in this case is the fact in c you use unsigned numbers and java has only signed numbers. While you can implement the same algorithm with signed numbers, you have to be aware of the fact the sign bit is carried over on shift operations, requiring an extra "and".

    This is my implementation:

    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;
    
    }
    
    0 讨论(0)
提交回复
热议问题