Igor Orekhov Igor Orekhov - 5 months ago 143
Java Question

Calculate low and high bytes CRC16 - Java

I encountered with the issue with CRC16 algorithm. There is a string of hex 80 01 F0, after CRC16 I get the low byte = 23 and the high one = 80. So, the question is how to calculate these two bytes? I tried the CRC calculators but there was no result. Also, it would be perfect if there is an example of this method in Java.
In manual there is additional information:
Low and high byte of a forward CRC-16 algorithm using the Polynomial (X16 + X15 + X2 + 1) calculated on all bytes. It is initialised using the seed 0xFFFF.

Answer

Thank you for responses. I am confident my answer will be useful for others. Tested and working code.

    private static byte[] getCRC16LowHighBytes(byte[] byteSequence) {
    // Create a byte array for Low and High bytes
    byte[] returnBytes = new byte[2];
    int crc = CRC16_SEED;
    for (int i = 0; i < byteSequence.length; ++i) {
        crc ^= (byteSequence[i] << 8);
        for (int j = 0; j < 8; ++j) {
            if ((crc & 0x8000) != 0) {
                crc = (crc << 1) ^ CRC16_POLINOM;
            } else {
                crc <<= 1;
            }
        }
    }
    byte[] crcBytes = getBytes(crc);
    // The first two bytes of crcBytes are low and high bytes respectively.
    for (int i = 0; i < returnBytes.length; i++) {
        returnBytes[i] = crcBytes[i];
    }
    return returnBytes;
}

private static byte[] getBytes(int v) {
    byte[] writeBuffer = new byte[4];
    writeBuffer[3] = (byte) ((v >>> 24) & 0xFF);
    writeBuffer[2] = (byte) ((v >>> 16) & 0xFF);
    writeBuffer[1] = (byte) ((v >>> 8) & 0xFF);
    writeBuffer[0] = (byte) ((v >>> 0) & 0xFF);
    return writeBuffer;
}