CRC-CCITT validation in java (android)
Hi I have some data being received over a bluetooth connection. The data has a 16-bit CRC 16-CCITT block which I want to use in order to verify that the data was transferred successfully and without error. Is there any built in method in java or android that can help me or do I need to implement it myself? Will I need to encode the data and compare? I have a code snippet for doing that which I found online, but I'm not sure it is correct or efficient. It is found at: http://introcs.cs.princeton.edu/java/51data/CRC16CCITT.java.html and the code is:
int crc = 0xFFFF; // initial value
int polynomial = 0x1021; // 0001 0000 0010 0001 (0, 5, 12)
// byte[] testBytes = "123456789".get开发者_开发技巧Bytes("ASCII");
byte[] bytes = args[0].getBytes();
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));
I also saw that Java has an implementation of crc32 at http://download.oracle.com/javase/1.4.2/docs/api/java/util/zip/CRC32.html. Is that something I can use here?
Thanks.
It is very inefficient. There is a table-driven version around the Internet written originally in C in the 1980s that runs at least 8 times as fast. The Wikipedia article appears to provide some links.
精彩评论