public class CRC16 {
private static final int POLY = 0x8005;
private static final int INIT = 0x0000;
private static final int XOROUT = 0x0000;
/**
*
* @param data 反转前数据
* @return
*/
public static int crc16(int[] data) {
// 数据反转
batchDataReverse(data, 8);
int crc = INIT;
for (int b : data) {
crc ^= (b & 0xFF) << 8;
for (int i = 0; i < 8; i++) {
if ((crc & 0x8000) != 0) {
crc = (crc << 1) ^ POLY;
} else {
crc <<= 1;
}
}
}
return dataReverse(crc & 0xFFFF ^ XOROUT, 16);
}
/**
*
* 批量反转
* @param data 待反转数据
*/
private static void batchDataReverse(int[] data, int byteLength) {
for (int i = 0; i < data.length; i++) {
data[i] = dataReverse(data[i], byteLength);
}
}
/**
*
* @param data
* @param byteLength 字节长度
* @return
*/
private static int dataReverse(int data, int byteLength) {
final String string = StringUtils.leftPad(Integer.toBinaryString(data), byteLength, "0");
final String reverse = StringUtils.reverse(string);
return Integer.parseInt(reverse, 2);
}
public static String strComputeCRC16(String strData){
// 字符串转int类型
final int[] ints1 = StringUtils.toCodePoints(strData);
int crc1 = crc16(ints1);
return StringUtils.leftPad(Integer.toHexString(crc1).toUpperCase(), 4, "0");
}
public static void main(String[] args) {
String str = "123";
final String s = strComputeCRC16(str);
}
}
所得结果与 CRC(循环冗余校验)在线计算_ip33.com CRC-16/IBM结果一致