我想將C CRC32代碼轉換爲java。下面的代碼就是我想到的。但它似乎工作方式不同。在C中計算的期望CRC32是13 82 D8 46),但下面的代碼的輸出是「最後的crc是-2084771805 in hex ffffffff83bce823」。有人能告訴我爲什麼嗎?CRC32與在java中籤名的字節
C代碼
uint32 crc32_update(uint32 crc, const uint8_t *data, uint16 data_len)
{
uint16_t tbl_idx;
while (data_len--) {
tbl_idx = crc^(*data >> (0 * 4));
crc = crc_table[tbl_idx & 0x0f]^(crc >> 4);
tbl_idx = crc^(*data >> (1 * 4));
crc = crc_table[tbl_idx & 0x0f]^(crc >> 4);
data++;
}
return crc & 0xffffffff;
}
JAVA代碼。
public class crc32trial_3 {
static final long crc_table[] = new long[] {
0x00000000, 0x1db71064, 0x3b6e20c8, 0x26d930ac,
0x76dc4190, 0x6b6b51f4, 0x4db26158, 0x5005713c,
0xedb88320, 0xf00f9344, 0xd6d6a3e8, 0xcb61b38c,
0x9b64c2b0, 0x86d3d2d4, 0xa00ae278, 0xbdbdf21c
};
public static long crc32_init()
{
return 0xffffffff;
}
private static long crc32_update(long crc, byte[] data, int data_len)
{
int tbl_idx;
for(int i = 0 ; i < data_len ; i ++) {
tbl_idx = (int)crc^(data[i] >> (0 * 4));
crc = crc_table[tbl_idx & 0x0f]^(crc >> 4);
tbl_idx = (int)crc^(data[i] >> (1 * 4));
crc = crc_table[tbl_idx & 0x0f]^(crc >> 4);
//data++;
}
return crc & 0xffffffff;
}
public static void main(String args[])
{
long intialcrc = crc32_init();
long crc;
System.out.println("the intail crc = " + intialcrc);
byte[] packets = new byte[]{ 88,0,1,0,0,0,0,0,0,0,0,0,-1,-1,-1,-1,1,0,0,0,-1,-1,-1,-1,0,0,-56,-46,-117,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,-1,0,-68,118 };
byte[] totalLenght = new byte[]{100,0,0,0};
byte[] totalSettingBlock = new byte[]{2};
crc = crc32_update(intialcrc,totalLenght,4);
crc = crc32_update(crc, totalSettingBlock,1);
int temp = 28 + 72;
crc = crc32_update(crc,packets, temp);
long finalcrc = crc;
System.out.println(" the final crc is " + finalcrc + " in hex " + Long.toHexString(finalcrc));
}
}
['java.util.zip.CRC32'](http://docs.oracle.com/javase/8/docs/api/java/util/zip/CRC32.html)確實存在。 [代碼可用](http://grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/8-b132/java/util/zip/CRC32.java#CRC32) 。 – 2015-02-09 08:26:52
然後向右移動0 * 4會產生nohing。你有沒有錯誤地複製你的源代碼? – EJP 2015-02-09 08:51:05
我試過但crc.reset()將初始值設置爲0,但我要求它是-1。 – Developer 2015-02-09 09:05:40