Skip to content

Instantly share code, notes, and snippets.

@gythialy
Last active August 29, 2015 14:20
Show Gist options
  • Select an option

  • Save gythialy/4e2713b5d8e792be8ae1 to your computer and use it in GitHub Desktop.

Select an option

Save gythialy/4e2713b5d8e792be8ae1 to your computer and use it in GitHub Desktop.
CDT91 crc
import com.google.common.io.BaseEncoding;
public class CRC8 {
private static byte[] CRC_TABLE = new byte[256];
static {
init();
}
static void init() {
byte temp = 0;
for (short i = 0; i < 256; i++) {
temp = (byte) i;
for (byte j = 0; j < 8; j++) {
if ((temp & 0x80) != 0) {
temp = (byte) (temp << 1);
temp = (byte) (temp ^ 0x7);
} else {
temp = (byte) (temp << 1);
}
}
CRC_TABLE[i] = temp;
}
}
/**
* 获取CRC校验码(算式是0x107)
*
* @param data
* 需要计算校验的数组
* @param startIndex
* 开始校验位
* @param length
* 进行校验的字节总长度
* @return CRC8校验
*/
public static byte crc(byte[] data, int startIndex, int length) {
byte returnValue = 0;
int index = 0;
for (int i = startIndex; i < startIndex + length; i++) {
returnValue = (byte) (returnValue ^ data[i]);
index = returnValue;
if (returnValue < 0) {
index = (returnValue & 0xff);
}
returnValue = CRC_TABLE[index];
}
returnValue = (byte) (returnValue ^ 0xff);
return (byte) returnValue;
}
/**
* 获取CRC校验码(算式是0x107)
*
* @param data
* 需要计算校验的数组
* @return CRC8校验
*/
public static byte crc(byte[] data) {
return crc(data, 0, data.length);
}
public static void main(String[] args) {
byte[] decode = BaseEncoding.base16().withSeparator(" ", 2).decode("01 C8 00 9C FF");
byte crc = crc(decode);
System.out.println(BaseEncoding.base16().withSeparator(" ", 2).encode(decode)
+ " "
+ Integer.toHexString(0x00ff & crc));
}
}
@gythialy
Copy link
Copy Markdown
Author

gythialy commented May 7, 2015

EB 90 EB 90 EB 90 71 61 02 01 01 84 00 FC 2F FF 7F BD 01 00 80 9C FF 78
EB 90 EB 90 EB 90 71 C2 02 01 01 41 00 FF 07 9C 0F 08 01 C8 00 64 00 26
EB 90 EB 90 EB 90 71 B3 02 01 01 65 00 FF 0F C4 09 EF 01 C8 00 9C FF 69

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment