最近碰到个 CRC-CCITT (Kermit)校验算法,于是我百度一顿操作,毫无结果。没找到任何JAVA版本的 CRC-CCITT (Kermit),其他的语言也少!终于在一个神奇的地方找到了一个C语言版本,翻译过来如下,特此分享!
C版本原址:http://www.lammertbies.nl/comm/info/crc-calculation.html
public class Crc {
private static final int POLYNOMIAL = 0x8408;
private static final int PRESET = 0;
static private int[] tab;
static {
tab = new int[256];
for (int i = 0; i < 256; i++) {
tab[i] = initial((byte) i);
}
}
private static int initial(byte c) {
int crc = 0;
for (int j = 0; j < 8; j++) {
if (((crc ^ c) & 1) == 1) {
crc = ((crc >> 1) ^ POLYNOMIAL);
} else {
crc = (crc >> 1);
}
c = (byte) (c >> 1);
}
return crc;
}
private static int update_crc(int crc, byte c) {
int cc = (0xff & c);
int tmp = (crc ^ cc);
crc = (crc >> 8) ^ tab[tmp & 0xff];
return crc;
}
private static int swab(int n) {
return (((n & 0xFF00) >> 8) + ((n & 0xFF) << 8));
}
public static int crc(String str) {
return crcb(str.getBytes());
}
public static int crcb(byte... i) {
int crc = PRESET;
for (byte c : i) {
crc = update_crc(crc, c);
}
return swab(crc);
}
public static void main(String[] args) {
int crc = Crc.crcb((byte) 0xFC, (byte) 5, (byte) 0x11);
System.out.println(Integer.toHexString(crc));
crc = Crc.crc("123456789");//结果是0x8921
System.out.println(Integer.toHexString(crc));
}
}