我需要将C
CRC16 方法转换为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 是否正确?
编辑:
修改后crc16
的工作方法(感谢出色的答案):
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。使用收到的方法执行此crc
操作dec2m(crc, 16)
:
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;
}
为了测试你的结果,你可以使用这个网站(感谢@greenaps)