diff --git a/li.strolch.utils/src/main/java/li/strolch/utils/Crc.java b/li.strolch.utils/src/main/java/li/strolch/utils/Crc.java index b79d4b1d1..c7c10f4e5 100644 --- a/li.strolch.utils/src/main/java/li/strolch/utils/Crc.java +++ b/li.strolch.utils/src/main/java/li/strolch/utils/Crc.java @@ -5,7 +5,8 @@ import static li.strolch.utils.helper.ByteHelper.toByteArrayBigEndian; /** *

Implements Cyclic Redundancy Checks

* - *

Fast byte-wise CRC16 calculation, using the code from Christian d'Heureuse, Inventec Informatik AG, Switzerland, www.source-code.biz

+ *

Fast byte-wise CRC16 calculation, using the code from Christian d'Heureuse, Inventec Informatik AG, Switzerland, + * www.source-code.biz

*/ public class Crc { @@ -41,6 +42,24 @@ public class Crc { return toByteArrayBigEndian(crcCcittBytes(bytes)); } + /** + * Implements a CRC-CCITT (XModem), using the initial value 0x0000 and the polynomial 0x1021 + * + * @param bytes + * the bytes to CRC + * @param src + * start if array to do CRC + * @param length + * end in array to do CRC + * + * @return the 2 byte CRC + * + * @see crc-calculation + */ + public static byte[] crcCcitt(byte[] bytes, int src, int length) { + return toByteArrayBigEndian(crcCcittBytes(bytes, src, length)); + } + /** * Implements a CRC-CCITT (XModem), using the initial value 0x0000 and the polynomial 0x1021 * @@ -52,8 +71,27 @@ public class Crc { * @see crc-calculation */ public static short crcCcittBytes(byte[] bytes) { + return crcCcittBytes(bytes, 0, bytes.length); + } + + /** + * Implements a CRC-CCITT (XModem), using the initial value 0x0000 and the polynomial 0x1021 + * + * @param bytes + * the bytes to CRC + * @param src + * start if array to do CRC + * @param length + * end in array to do CRC + * + * @return the CRC as short + * + * @see crc-calculation + */ + public static short crcCcittBytes(byte[] bytes, int src, int length) { int crc = 0x0000; - for (byte aData : bytes) { + for (int i = src; i < length; i++) { + byte aData = bytes[i]; crc = ((crc << 8) & 0xFF00) ^ (crcTable[(crc >> 8) ^ (aData & 0xFF)] & 0xFFFF); } return (short) crc; diff --git a/li.strolch.utils/src/test/java/li/strolch/utils/Crc16Test.java b/li.strolch.utils/src/test/java/li/strolch/utils/Crc16Test.java index 60f8e8852..a65b91cd6 100644 --- a/li.strolch.utils/src/test/java/li/strolch/utils/Crc16Test.java +++ b/li.strolch.utils/src/test/java/li/strolch/utils/Crc16Test.java @@ -33,4 +33,11 @@ public class Crc16Test { byte[] expected = { 0x77, (byte) 0x83 }; assertArrayEquals(expected, Crc.crcCcitt(data)); } + + @Test + public void shouldCrc16_4() { + byte[] data = { 0x20, (byte) 0x80, 0x00, 0x00, 0x03, 0x00, 0x30 }; + byte[] expected = { 0x77, (byte) 0x83 }; + assertArrayEquals(expected, Crc.crcCcitt(data, 1, data.length - 1)); + } }