crc16实现java

Ali*_*gul 5 implementation byte crc rfid crc16

我在java中计算字节数组的CRC-16实现时遇到问题.基本上我试图将字节发送到开始写入标签的RFID.我可以通过在mac上查看tcpdump命令来查看数组的校验和值.但我的目标是自己生成它.这是我的字节数组,它应该生成0xbe,0xd9:

byte[] bytes = new byte[]{(byte) 0x55,(byte) 0x08,(byte) 0x68, (byte) 0x14, 
                          (byte) 0x93, (byte) 0x01, (byte) 0x00, (byte) 0x00, 
                          (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x06, 
                          (byte) 0x00, (byte) 0x00, (byte) 0x01, (byte) 0x00, 
                          (byte) 0x13, (byte) 0x50, (byte) 0x00, (byte) 0x00, 
                          (byte) 0x00, (byte) 0x22, (byte) 0x09, (byte) 0x11};
Run Code Online (Sandbox Code Playgroud)

0x55是标题.正如文档所说,它将被排除在外.

每当我在java上尝试这个数组(使用0xbe,0xd9)时,RFID都可以工作.我的问题是生成那些校验和值.我搜索了几乎整个网络,但没有机会.我找不到任何产生0xbe,0xd9的算法.

任何想法都是我最受欢迎的.提前致谢.

编辑:这是 rfid提供的协议

Rob*_*tti 3

不是确定这是否是 C crc16 算法在 Java 中的正确翻译....但它显示了您的示例的正确结果!

请在使用前将其他结果与Mac的CRC16进行比较并进行压力测试。

public class Crc16 {
public static void main(String... a) {
    byte[] bytes = new byte[] { (byte) 0x08, (byte) 0x68, (byte) 0x14, (byte) 0x93, (byte) 0x01, (byte) 0x00,
            (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x06, (byte) 0x00, (byte) 0x00, (byte) 0x01,
            (byte) 0x00, (byte) 0x13, (byte) 0x50, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x22, (byte) 0x09,
            (byte) 0x11 };
    byte[] byteStr = new byte[4];
    Integer crcRes = new Crc16().calculate_crc(bytes);
    System.out.println(Integer.toHexString(crcRes));

    byteStr[0] = (byte) ((crcRes & 0x000000ff));
    byteStr[1] = (byte) ((crcRes & 0x0000ff00) >>> 8);

    System.out.printf("%02X\n%02X", byteStr[0],byteStr[1]);
} 

int calculate_crc(byte[] bytes) {
    int i;
    int crc_value = 0;
    for (int len = 0; len < bytes.length; len++) {
        for (i = 0x80; i != 0; i >>= 1) {
            if ((crc_value & 0x8000) != 0) {
                crc_value = (crc_value << 1) ^ 0x8005;
            } else {
                crc_value = crc_value << 1;
            }
            if ((bytes[len] & i) != 0) {
                crc_value ^= 0x8005;
            }
        }
    }
    return crc_value;
}

}
Run Code Online (Sandbox Code Playgroud)