我需要将CCRC16方法转换为Java。问题是我不太擅长C和字节操作。
C代码:

static const unsigned short crc16_table[256] =
{
 0x0000,0xC0C1,0xC181,0x0140,0xC301,0x03C0,0x0280,0xC241,
 ...  /* Removed for brevity */
 0x8201,0x42C0,0x4380,0x8341,0x4100,0x81C1,0x8081,0x4040
};

unsigned short crc16 (const void *data, unsigned data_size)
{
 if (!data || !data_size)
 return 0;
 unsigned short crc = 0;
 unsigned char* buf = (unsigned char*)data;
 while (data_size--)
 crc = (crc >> 8) ^ crc16_table[(unsigned char)crc ^ *buf++];
 return crc;
}

这就是我想要改变的。不确定是否正确。
private static int[] table = {
    0x0000,0xC0C1,0xC181,0x0140,0xC301,0x03C0,0x0280,0xC241,0xC601,0x06C0,0x0780,0xC741,
    ...    // Removed for brevity
    0x4400,0x84C1,0x8581,0x4540,0x8701,0x47C0,0x4680,0x8641,0x8201,0x42C0,0x4380,0x8341, 0x4100,0x81C1,0x8081,0x4040
};

public static int getCode (String[] data){
    if (data.length == 0) {
        return 0;
    }
    int crc = 0;
    for (String item : data) {
        byte[] bytes = item.getBytes();
        for (byte b : bytes) {
            crc = (crc >>> 8) ^ table[(crc ^ b) & 0xff]; //this confuses me
        }
    }
    return crc;
}

问题:
我的Java移植是否正确?
编辑:
改进的工作方法(多亏了很好的答案):
public static int getCode(String data) {
    if (data == null || data.equals("")) {
        return 0;
    }
    int crc = 0x0000;
    byte[] bytes = data.getBytes();
    for (byte b : bytes) {
        crc = (crc >>> 8) ^ table[(crc ^ b) & 0xff];
    }
    return crc;
}

这将返回十进制值。CRC16代码需要十六进制。我用这个方法把基数转换成16。用接收到的crc16crc这样做:
static String dec2m(int N, int m) {
    String s = "";
    for (int n = N; n > 0; n /= m) {
        int r = n % m;
        s = r < 10 ? r + s : (char) ('A' - 10 + r) + s;
    }
    return s;
}

为了测试您的结果,您可以使用this site(感谢@greenaps)

最佳答案

你翻译的c代码函数调用错误。

public static int getCode (String[] data)

应该是
public static int getCode (String data)

此外,您还可以在Wialon pdf中看到,您需要crc16 (const void *data, unsigned data_size)而不是getCode (String)
将接收到的字符串转换为字节数组。

10-08 13:34