[Minor] Added methods with src and length in Crc.java

This commit is contained in:
Robert von Burg 2018-06-27 18:31:47 +02:00
parent 466838d73b
commit 78b0c579bf
2 changed files with 47 additions and 2 deletions

View File

@ -5,7 +5,8 @@ import static li.strolch.utils.helper.ByteHelper.toByteArrayBigEndian;
/**
* <p>Implements Cyclic Redundancy Checks</p>
*
* <p>Fast byte-wise CRC16 calculation, using the code from Christian d'Heureuse, Inventec Informatik AG, Switzerland, www.source-code.biz</p>
* <p>Fast byte-wise CRC16 calculation, using the code from Christian d'Heureuse, Inventec Informatik AG, Switzerland,
* www.source-code.biz</p>
*/
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 <a href="https://www.lammertbies.nl/comm/info/crc-calculation.html">crc-calculation</a>
*/
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 <a href="https://www.lammertbies.nl/comm/info/crc-calculation.html">crc-calculation</a>
*/
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 <a href="https://www.lammertbies.nl/comm/info/crc-calculation.html">crc-calculation</a>
*/
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;

View File

@ -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));
}
}