用JAVA实现CRC校验。
输入byte型的数组,产生两个元素的byte型数组(也就是16位)
public static byte[] makefcs(byte[] data) { int crc=0xFFFF; byte[] buf = new byte[data.length];// 存储需要产生校验码的数据 byte[] bup=new byte[2]; for (int i = 0; i < data.length; i++) { buf[i] = data[i]; //数据的复制 } int len = buf.length; for (int pos = 0; pos < len; pos++) { if (buf[pos] < 0) { crc ^= (int) buf[pos] + 256; //^异或:用于位运算,每个位相同为0,不同为1 } else { crc ^= (int) buf[pos]; } for (int i = 8; i != 0; i--) { if ((crc & 0x0001) != 0) { crc >>= 1; //右移运算符 crc ^= 0xA001; } else crc >>= 1; } } String c = Integer.toHexString(crc); if (c.length() == 4) { c = c.substring(2, 4) + c.substring(0, 2); } else if (c.length() == 3) { c = "0" + c; c = c.substring(2, 4) + c.substring(0, 2); } else if (c.length() == 2) { c = "0" + c.substring(1, 2) + "0" + c.substring(0, 1); } bup[0]=(byte)(Integer.parseInt(c.substring(0, 1), 16)+Integer.parseInt(c.substring(1,2), 16)); bup[1]=(byte)(Integer.parseInt(c.substring(2, 3), 16)+Integer.parseInt(c.substring(3,4), 16)); return bup; }
文章来源: JAVA之CRC校验算法