Search code examples
javaandroidcrc16

How to get Good CRC16 from string in java?


I am trying to get CRC16 from string in android application using following code

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;

}

and I have some data to verify the result as below table

expected result

when I am passing A to that function I am getting B915 which is bad CRC and same for all. why I am not able to get Good CRC as mentioned in table. please correct me where I am doing wrong? Thanks!


Solution

  • You are getting a Bad_CRC because you are calculating Bad_CRC by using 0xFFFF. If you want to calculate Good_CRC then replace it with 0x1D0F.

    enter image description here

    Here is the code snippet:

    public static void main(String[] args) { 
        String input = "A";
        Integer crcRes = crc16(input.getBytes());
        System.out.println("Calculated CRC-CCITT: 0x" + Integer.toHexString(crcRes));
    }
    
    private static int crc16(final byte[] buffer) {
        /* Note the change here */
        int crc = 0x1D0F;
        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;
    }
    

    Output:

    Calculated CRC-CCITT: 0x9479