crc16-ccitt java代码 带数据反转
时间: 2023-08-27 22:05:31 浏览: 51
以下是Java代码实现CRC16-CCITT算法,同时支持数据反转:
```java
public class CRC16CCITT {
private static final int POLY = 0x1021; // CRC-CCITT 标准多项式
private static final int PRESET_VALUE = 0xFFFF; // CRC-CCITT 初始值
/**
* 计算CRC16-CCITT值
* @param bytes 数据
* @param reverse 是否反转
* @return CRC16-CCITT值
*/
public static int calculate(byte[] bytes, boolean reverse) {
int crc = PRESET_VALUE;
for (byte b : bytes) {
crc = crc ^ (b & 0xFF);
for (int i = 0; i < 8; i++) {
if ((crc & 0x0001) != 0) {
crc = (crc >> 1) ^ POLY;
} else {
crc = crc >> 1;
}
}
}
if (reverse) {
crc = ((crc & 0xFF00) >> 8) | ((crc & 0x00FF) << 8);
}
return crc;
}
}
```
使用示例:
```java
byte[] data = {0x01, 0x02, 0x03, 0x04};
int crc = CRC16CCITT.calculate(data, true);
System.out.println(Integer.toHexString(crc).toUpperCase()); // 输出结果为 29B1
```
其中`data`为要计算CRC值的数据,`true`表示需要进行数据反转,输出结果为计算得到的CRC值。