Last active
August 29, 2015 14:20
-
-
Save gythialy/4e2713b5d8e792be8ae1 to your computer and use it in GitHub Desktop.
CDT91 crc
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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)); | |
| } | |
| } |
Author
gythialy
commented
May 7, 2015
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment