public static int getCrc(byte[] bytes, int begin, int end) { int result = 0; boolean escapeHot = false; for (int index = begin; index <= end; index++) { byte data = bytes[index]; if (data == (byte) BidibLibrary.BIDIB_PKT_ESCAPE) { escapeHot = true; } else { if (escapeHot) { data ^= 0x20; escapeHot = false; } result = CRC8.getCrcValue((data ^ result) & 0xFF); } } return result; }
public FirmwarePacket(String line) { // line must start with ':' if (line.charAt(0) != ':') { throw new IllegalArgumentException("Line of Intel hex must start with ':'"); } byte[] dataLine = ByteUtils.parseHexBinary(line.substring(1)); len = dataLine[0]; targetAddress = ByteUtils.getInt(dataLine[2], dataLine[1]); target = (ByteUtils.getInt(dataLine[3]) == 0 ? Target.flash : Target.eeprom); data = ByteUtils.subArray(dataLine, 4, dataLine.length - 5); crc = dataLine[dataLine.length - 1]; // check the crc int calcCRC = CRC8.getIntelCrc(dataLine, 0, dataLine.length - 1); if (crc != calcCRC) { LOGGER.error("The calculated CRC ({}) does not matched the provided CRC ({})", calcCRC, crc); throw new IllegalArgumentException("CRC check failed."); } }
public static void encodeMessage(final ByteArrayOutputStream data, final OutputStream output) throws IOException { byte[] message = data.toByteArray(); // encode all messages sendDelimiter(output); int index = 0; int totalLen = message.length; int txCrc = 0; while (index < totalLen) { // get the length byte length = message[index++]; escape(output, length); txCrc = CRC8.getCrcValue((length ^ txCrc) & 0xFF); for (int i = index; i <= (length + index - 1); i++) { escape(output, message[i]); txCrc = CRC8.getCrcValue((message[i] ^ txCrc) & 0xFF); } index += length; } escape(output, ByteUtils.getLowByte(txCrc)); sendDelimiter(output); }
int crcIndex = 0; for (crcIndex = 0; crcIndex < output.length - 1; crcIndex++) { crc = CRC8.getCrcValue((output[crcIndex] ^ crc) & 0xFF);
int txCrc = CRC8.getCrcValue(length); txCrc = CRC8.getCrcValue((message[i] ^ txCrc) & 0xFF);