Android CRC-CCITT

2020-06-06 07:18发布

I need a CRC check for an application Im writing, but cant figure out for the online code and calculators what im doing wrong. I may just not understand it correctly. This is what I need :

It uses CRC-CCITT with a starting value of 0xFFFF with reverse input bit order. For example, the Get Device Type message is: 0x01, 0x06, 0x01, 0x00, 0x0B, 0xD9. The CRC is 0xD90B.

And this is the code Im using :

public static int CRC16CCITT(byte[] bytes) {
    int crc = 0xFFFF;          // initial value
    int polynomial = 0x1021;   // 0001 0000 0010 0001  (0, 5, 12) 

    for (byte b : bytes) {
        for (int i = 0; i < 8; i++) {
            boolean bit = ((b   >> (7-i) & 1) == 1);
            boolean c15 = ((crc >> 15    & 1) == 1);
            crc <<= 1;
            if (c15 ^ bit) crc ^= polynomial;
         }
    }

    crc &= 0xffff;
    //System.out.println("CRC16-CCITT = " + Integer.toHexString(crc));
    return crc;

Im writing it for an Android device so needs to be in java.

标签: android crc
1条回答
Bombasti
2楼-- · 2020-06-06 08:02

Here is the code that I use in my App (It works).

static public int GenerateChecksumCRC16(int bytes[]) {

        int crc = 0xFFFF;
        int temp;
        int crc_byte;

        for (int byte_index = 0; byte_index < bytes.length; byte_index++) {

            crc_byte = bytes[byte_index];

            for (int bit_index = 0; bit_index < 8; bit_index++) {

                temp = ((crc >> 15)) ^ ((crc_byte >> 7));

                crc <<= 1;
                crc &= 0xFFFF;

                if (temp > 0) {
                    crc ^= 0x1021;
                    crc &= 0xFFFF;
                }

                crc_byte <<=1;
                crc_byte &= 0xFF;

            }
        }

        return crc;
    }
查看更多
登录 后发表回答