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;
}
これは Decimal 値を返します。また、CRC16 コードは 16 進数である必要があります。このメソッドを使用して、base 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 に感謝)