将CRC16 C#代码转换为Java CRC16
我有一个计算字节数组上CRC16的C代码:将CRC16 C#代码转换为Java CRC16,java,c#,crc16,Java,C#,Crc16,我有一个计算字节数组上CRC16的C代码: public static byte[] CalculateCRC(byte[] data) { ushort crc = 0; ushort temp = 0; for (int i = 0; i < data.Length; i++) { ushort value = (ushort)data[i]; temp
public static byte[] CalculateCRC(byte[] data)
{
ushort crc = 0;
ushort temp = 0;
for (int i = 0; i < data.Length; i++)
{
ushort value = (ushort)data[i];
temp = (ushort)(value ^ (ushort)(crc >> 8));
temp = (ushort)(temp ^ (ushort)(temp >> 4));
temp = (ushort)(temp ^ (ushort)(temp >> 2));
temp = (ushort)(temp ^ (ushort)(temp >> 1));
crc = (ushort)((ushort)(crc << 8) ^ (ushort)(temp << 15) ^ (ushort)(temp << 2) ^ temp);
}
byte[] bytes = new byte[] { (byte)(CRC >> 8), (byte)CRC };
return bytes;
}
应该返回{86216}
提前谢谢 A
ushort
是16位,而Achar
是8位。因此,Java版本不可能具有相同的中间值。使用int
,它可以很好地存储16位值
如果使用int,则需要将每个循环的结果截断为16位,因此放入
crc&=0xffff代码>在循环结束之前。Java类型字节的范围为-128、…、127。对于您的测试数据,我甚至无法编译。@TobiasBrösamle将上述示例作为int数组,并使用(byte)intValue将其转换为byte数组。我无法使用C代码获得该结果。
public static byte[] calculateCrc16(byte[] data)
{
char crc = 0x0000;
char temp;
byte[] crcBytes;
for(int i = 0; i<data.length;++i)
{
char value = (char) (data[i] & 0xFF);
temp = (char)(value ^ (char) (crc >> 8));
temp = (char)(temp ^ (char) (temp >> 4));
temp = (char)(temp ^ (char) (temp >> 2));
temp = (char)(temp ^ (char) (temp >> 1));
crc = (char) ((char)(crc << 8)^ (char)(temp <<15) ^ (char)(temp << 2) ^ temp);
} //END of for loop
crcBytes = new byte[]{(byte)((crc<<8) & 0x00FF), (byte)(crc & 0x00FF)};
return crcBytes;
}
{
48, 48, 56, 50, 126, 49, 126, 53, 53, 53, 126, 53, 126, 54, 48, 126,
195, 120, 202, 249, 35, 221, 44, 162, 7, 191, 207, 64, 31, 144, 88,
62, 201, 51, 191, 234, 82, 62, 226, 1, 69, 186, 192, 26, 171, 197, 229,
247, 180, 155, 255, 228, 86, 213, 255, 254, 215, 89, 53, 96, 186, 49, 135,
185, 0, 19, 103, 168, 44, 8, 203, 154, 150, 237, 234, 176, 110, 113, 154
}