c++、java CRC16算法

本文介绍了一种计算CRC16校验码的方法,并提供了C++和Java两种语言的具体实现。通过对比验证,这两种实现方式得到相同的结果,确保了算法的正确性和一致性。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

c++代码

int get_crc16 (unsigned char *bufData, unsigned int buflen, unsigned char *pcrc)
{
  int ret = 0;
  unsigned short CRC = 0xffff;
  unsigned short POLYNOMIAL = 0xa001;
  int i, j;


  if(bufData == NULL || pcrc == NULL)
  {
    return -1;
  }

  if (buflen == 0)
  {
    return ret;
  }
  for (i = 0; i < buflen; i++)
  {
    CRC ^= bufData[i];
    for (j = 0; j < 8; j++)
    {
      if ((CRC & 0x0001) != 0)
      {
        CRC >>= 1;
        CRC ^= POLYNOMIAL;
      }
      else
      {
        CRC >>= 1;
      }
    }
  }

  
  printf ("CRC=%X\n", CRC);
  pcrc[0] = (unsigned char)(CRC & 0x00ff);
  pcrc[1] = (unsigned char)(CRC >> 8);

  return ret;
}

int main(int argc, char *argv[])
{
  
  unsigned char cc[]={0x30,0x30,0x34,0x36,0x46,0x44,0x36,0x30,0x30,0x30,0x01,0x72,0x65,
    0x66,0x65,0x72,0x69,0x6E,0x66,0x6F,0x2E,0x63,0x73,0x76,0x00,0x00
    ,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00
    ,0x00,0x00,0x00,0x01,0xf4,0x01};
    
  //unsigned char cc[] = {0x00, 0xff};
  unsigned char crcs[3] = {0};
  int ret = get_crc16 (cc, 46, crcs);
  printf("ret = %d\n", ret);
  return 0;
}
java代码
public static int get_crc16 (byte[] bufData, int buflen, byte[] pcrc)
  {
    int ret = 0;
    int CRC = 0x0000ffff;
    int POLYNOMIAL = 0x0000a001;
    int i, j;


    if (buflen == 0)
    {
      return ret;
    }
    for (i = 0; i < buflen; i++)
    {
      CRC ^= ((int)bufData[i] & 0x000000ff);
      for (j = 0; j < 8; j++)
      {
        if ((CRC & 0x00000001) != 0)
        {
          CRC >>= 1;
          CRC ^= POLYNOMIAL;
        }
        else
        {
          CRC >>= 1;
        }
      }
      //System.out.println(Integer.toHexString(CRC));
    }
    
    System.out.println(Integer.toHexString(CRC));
    pcrc[0] = (byte)(CRC & 0x00ff);
    pcrc[1] = (byte)(CRC >> 8);

    return ret;
  }
  /**
   * @param args
   */
  public static void main(String[] args) {
    byte[] aa = {0x30,0x30,0x34,0x36,0x46,0x44,0x36,0x30,0x30,0x30,0x01,0x72,0x65,
        0x66,0x65,0x72,0x69,0x6E,0x66,0x6F,0x2E,0x63,0x73,0x76,0x00,0x00
        ,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00
        ,0x00,0x00,0x00,0x01,(byte)0xf4,0x01};
    byte[] bb = new byte[3];
    Crc16.get_crc16(aa, aa.length, bb);
    
    System.out.println(Integer.toHexString((int)bb[0] & 0x000000ff));
    System.out.println(Integer.toHexString((int)bb[1] & 0x000000ff));
    

  }

经过验证c++和java计算的结果是一样的。可以放心使用。


原文地址:http://www.tuicool.com/articles/2Eby6j

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值