简体   繁体   English

计算低字节和高字节CRC16-Java

[英]Calculate low and high bytes CRC16 - Java

I encountered with the issue with CRC16 algorithm. 我遇到了CRC16算法的问题。 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? 有一个十六进制的字符串80 01 F0,在CRC16之后,我得到低字节= 23而高字节=80。那么,问题是如何计算这两个字节? I tried the CRC calculators but there was no result. 我尝试了CRC计算器,但没有结果。 Also, it would be perfect if there is an example of this method in Java. 另外,如果在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. 在手册中还有其他信息:使用在所有字节上计算的多项式(X16 + X15 + X2 + 1)的正向CRC-16算法的低字节和高字节。 It is initialised using the seed 0xFFFF. 它使用种子0xFFFF初始化。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM