3

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!

Jignesh Ansodariya
  • 12,583
  • 24
  • 81
  • 113

1 Answers1

0

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
user2004685
  • 9,548
  • 5
  • 37
  • 54
  • 2
    Thanks a lot! Its solved. – Jignesh Ansodariya Apr 02 '16 at 08:52
  • No. This is just a bandaid. The CCIT CRC-16 is defined as having an initial value of 0xffff. The only other initial value in common use is zero. Find the bug in your code and fix it. There are plenty of working examples available, including a table-driven algorithm that is eight times as fast, – user207421 Apr 02 '16 at 08:54
  • 2
    @EJP `0xFFFF` is used to calculate `Bad_CRC`. `0x1D0F` should be used to calculate `Good_CRC`. Kermit is one other variation of `CRC-CCITT`. I do not see any bug in this code. Correct me if I'm wrong. – user2004685 Apr 02 '16 at 08:57