日期:2014-05-20  浏览次数:20721 次

JAVA 实现 CRC16算法。已有C 和 C# 版本了。仅用JAVA实现即可
如题
我手头做一个上位机程序,需要发送命令集,其中就有一个 CRC16效验码的发送。
初涉CRC16 不太懂。时间紧迫。
网上找到的都不能直接用。

感谢各位帮帮忙

C版本的

#define PRESET_VALUE 0xFFFF
#define POLYNOMIAL 0x8408
unsigned int uiCrc16Cal(unsigned char const * pucY, unsigned char ucX)
{
unsigned char ucI,ucJ;
unsigned short int uiCrcValue = PRESET_VALUE;

  for(ucI = 0; ucI < ucX; ucI++)
{
uiCrcValue = uiCrcValue ^ *(pucY + ucI);
for(ucJ = 0; ucJ < 8; ucJ++)
{
if(uiCrcValue & 0x0001)
{
uiCrcValue = (uiCrcValue >> 1) ^ POLYNOMIAL;
}
else
{
uiCrcValue = (uiCrcValue >> 1);
}
}
  }
return uiCrcValue;
}



C#版本的  
public class Crc16
  {
  private const ushort polynomial = 0x8408;
  private ushort[] table = new ushort[256];

  public ushort ComputeChecksum(byte[] bytes)
  {
  ushort crc = 0xffff;
  for (int i = 0; i < bytes.Length; ++i)
  {
  byte index = (byte)(crc ^ bytes[i]);
  crc = (ushort)((crc >> 8) ^ table[index]);
  }
  return crc;
  }

  public Crc16()
  {
  ushort value;
  ushort temp;
  for (ushort i = 0; i < table.Length; ++i)
  {
  value = 0;
  temp = i;
  for (byte j = 0; j < 8; ++j)
  {
  if (((value ^ temp) & 0x0001) != 0)
  {
  value = (ushort)((value >> 1) ^ polynomial);
  }
  else
  {
  value >>= 1;
  }
  temp >>= 1;
  }
  table[i] = value;
  }
  }
  }

可以用 04 00 01 验证。 计算出的CRC16低字节为 DB 高字节为 4B
也可以用 0B 00 01 01 01 04 EE 35 45 45 验证。 结果为 3A 3E 前低为 后高位

感谢


------解决方案--------------------
Java code

public class Crc16 {
    
    private final int polynomial = 0x8408;
    
    private int[] table = new int[256];
    
    public int ComputeChecksum(int[] bytes) {
        int crc = 0xffff;
        for (int i = 0; i < bytes.length; ++i) {
            int index = (crc ^ bytes[i]) % 256;
            crc = (crc >> 8) ^ table[index];
        }
        return crc;
    }
    
    public Crc16() {
        int value;
        int temp;
        for (int i = 0; i < table.length; ++i) {
            value = 0;
            temp = i;
            for (byte j = 0; j < 8; ++j) {
                if (((value ^ temp) & 0x0001) != 0) {
                    value = (value >> 1) ^ polynomial;
                } else {
                    value >>= 1;
                }
                temp >>= 1;
            }
            table[i] = value;
        }
    }
    
    public static void main(String[] args) {
        Crc16 c = new Crc16();
        int[] arr = new int[]{0x4, 0x0, 0x1};
        System.out.println(Integer.toString(c.ComputeChecksum(arr), 16));
        arr = new int[]{0xB, 0x0, 0x1, 0x1, 0x1, 0x4, 0xEE, 0x35, 0x45, 0x45 };
        System.out.println(Integer.toString(c.ComputeChecksum(arr), 16));
    }
}