转换çCRC16到Java CRC16 [英] Convert C CRC16 to Java CRC16
问题描述
我目前工作的一个项目,有一个嵌入式系统通过无线电将数据发送到PC。数据包获得在最后一个CRC16校验和它的基于该算法计算:
I am currently working on a project, having an embedded system sending data to a PC via radio. The packets get a crc16 checksum at the end and it's calculated based on this algorithm:
uint16_t crc16 (const uint8_t * buffer, uint32_t size) {
uint16_t crc = 0xFFFF;
if (buffer && size)
while (size--)
{
crc = (crc >> 8) | (crc << 8);
crc ^= *buffer++;
crc ^= ((unsigned char) crc) >> 4;
crc ^= crc << 12;
crc ^= (crc & 0xFF) << 5;
}
return crc;
}
现在我正在寻找在Java中的等价。我已经找到一个很好的位置:
http://introcs.cs.princeton.edu/java/51data/CRC16CCITT .java.html
Now I am looking for an equivalent in Java. I already found a good one here: http://introcs.cs.princeton.edu/java/51data/CRC16CCITT.java.html
public class CRC16CCITT {
public static void main(String[] args) {
int crc = 0xFFFF; // initial value
int polynomial = 0x1021; // 0001 0000 0010 0001 (0, 5, 12)
// byte[] testBytes = "123456789".getBytes("ASCII");
byte[] bytes = args[0].getBytes();
for (byte b : bytes) {
for (int i = 0; i < 8; i++) {
boolean bit = ((b >> (7-i) & 1) == 1);
boolean c15 = ((crc >> 15 & 1) == 1);
crc <<= 1;
if (c15 ^ bit) crc ^= polynomial;
}
}
crc &= 0xffff;
System.out.println("CRC16-CCITT = " + Integer.toHexString(crc));
}
}
但随着我的C code这并不工作。
But this doesnt work with my C Code.
是任何人能够提供一个C和Java算法相当于一个适应或解决方案?
谢谢!
Is anybody able to deliver an adaption or solution for a C and Java equivalent algorithm? Thank you!
推荐答案
在这种情况下,Java和C之间的主要区别是在C使用无符号数和java只是符号数的事实。虽然你可以用符号数实现相同的算法,你必须要知道的符号位结转轮班作业的事实,需要一个额外的和
The major difference between java and c in this case is the fact in c you use unsigned numbers and java has only signed numbers. While you can implement the same algorithm with signed numbers, you have to be aware of the fact the sign bit is carried over on shift operations, requiring an extra "and".
这是我的执行:
static int crc16(final byte[] buffer) {
int crc = 0xFFFF;
for (int j = 0; j < buffer.length ; j++) {
crc = ((crc >>> 8) | (crc << 8) )& 0xffff;
crc ^= (buffer[j] & 0xff);//byte to int, trunc sign
crc ^= ((crc & 0xff) >> 4);
crc ^= (crc << 12) & 0xffff;
crc ^= ((crc & 0xFF) << 5) & 0xffff;
}
crc &= 0xffff;
return crc;
}
这篇关于转换çCRC16到Java CRC16的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!