由于近期和硬件设备进行通信。涉及到了crc校验位。设备要求crc-16/xmodem进行校验。
public static int CRC_XModem(byte[] bytes) { // initial value int crc = 0x00; int polynomial = 0x1021; for (int index = 0; index < bytes.length; index++) { byte b = bytes[index]; for (int i = 0; i < 8; i++) { boolean bit = ((b >> (7 - i) & 1) == 1); boolean c15 = ((crc >> 15 & 1) == 1); crc <<= 1; if (c15 ^ bit) crc ^= polynomial; } } crc &= 0xffff; return crc; } // crc:从16进制截下来的要校验的数据。orginCrc:16进制数据中自带的crc public static boolean verify(String crc, String orginCrc) { //HexUtil.hexStringToBytes==>把字符串转成16进制字节 crc = Integer.toHexString(CRC_XModem(HexUtil.hexStringToBytes(crc))); if (crc.equalsIgnoreCase(orginCrc)) { return true; } return false; }
crc校验位可以保证通信传输过程中数据的准确性,判断数 据有无丢失