我在计算java中字节数组的CRC-16实现时遇到了问题。基本上,我尝试将字节发送到开始写入标签的RFID。我可以通过在mac上查看tcpdump命令来查看array的校验和值。但我的目标是自己生成它。下面是我的字节数组,它应该生成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};0x55是报头。正如文档所说,它将被排除在外。
每当我在java (使用0xbe,0xd9)上尝试这个数组时,RFID都能工作。我的问题是这些校验和值的生成。我几乎搜索了整个网络,但没有机会。我找不到任何产生0xbe,0xd9的算法。
任何想法对我来说都是最受欢迎的。提前谢谢。
编辑:随rfid提供的here is the protocol
发布于 2012-09-12 04:47:05
我不太确定这是不是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;
}
}发布于 2017-11-23 06:32:10
在Java运行时(rt.jar)中已经有了一个CRC16实现。
有关源代码,请参阅grepcode。
如果您搜索CRC16,您可能会在集成开发环境中看到它:

发布于 2012-09-11 22:43:32
也许你是在找这个?
Crc16 in java
我在这个方法中使用了相同的数组(变量"table"):
public Integer computeCrc16(byte[] data) {
int crc = 0x0000;
for (byte b : data) {
crc = (crc >>> 8) ^ table[((crc ^ b) & 0xff)];
}
return (int) crc;
}https://stackoverflow.com/questions/12372180
复制相似问题