我有一个在字节数组上计算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 = (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;
}现在,我必须用Java复制完全相同的逻辑。但是,我写的下面的代码没有给我预期的结果。
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;
}我不能找出我的java代码的逻辑错误。任何帮助都将不胜感激。
测试数据是以下字节数组
{
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
}应返回{86,216}
提前感谢!
发布于 2017-06-01 23:08:30
ushort是16位,而char是8位。因此,您的Java版本不可能具有相同的中间值。使用int,它可以很好地存储16位值。
如果您使用int,那么对于每个循环,您将需要将结果截断为16位,因此在循环结束之前放入一个crc &= 0xffff;。
https://stackoverflow.com/questions/44307570
复制相似问题