首页
学习
活动
专区
圈层
工具
发布

CRC计算
EN

Stack Overflow用户
提问于 2009-02-23 14:24:51
回答 3查看 4.7K关注 0票数 4

我正在尝试与第三方系统接口,他们提供了一个代码样本,用于在发送文本数据时计算CRC值。

供应商提供的C代码如下所示:

代码语言:javascript
复制
#define CRCRES 0xf0b8  /* residue for good verify */ 
#define DEBUG 

unsigned crctbl[] = {0x0000, 0x1081, 0x2102, 0x3183, 
                     0x4204, 0x5285, 0x6306, 0x7387, 
                     0x8408, 0x9489, 0xa50a, 0xb58b, 
                     0xc60c, 0xd68d, 0xe70e, 0xf78f}; 

/* 
 * This uses a 32 byte table to lookup the crc 4 bits at a time. 
 * The CRC CCITT is used. 
 */ 


unsigned short calc_crc(unsigned char *ptr, unsigned length) 

{ 
  unsigned short crc; 
  unsigned short i; 
  unsigned char pos,ch; 

  crc = 0xffff;  /* precondition crc */ 
  for (i = 0; i < length; i++,ptr++) { 
    ch = *ptr; 
    pos = (crc ^ ch) & 15; 
    crc = ((crc >> 4) & 0x0fff) ^ crctbl[pos]; 
    ch >>= 4; 
    pos = (crc^ch) & 15; 
    crc = ((crc >> 4) & 0xffff) ^ crctbl[pos]; 
  } 
  crc = ~crc;  /* post condition */ 
  crc = (crc << 8) | (crc >> 8); /* bytewise reverse */ 
  return crc; 
} 


/* 
 * tests the block of code containing the crc to verify it's 
 * content.  This compares to the reversed and inverted 
 * residue. 
 */ 

int test_crc(unsigned char *ptr, unsigned length) 

{ 
  unsigned short crc; 
  unsigned char arr [] = {'X','Y','Z'}; 

  crc = calc_crc(arr,3); 
  printf("Calced crc of test to be %04x, (should be 470f)\n", crc); 
  return (crc == 0x470f); 
} 

我已经复制了这段代码,并放入了一个示例C程序。test_crc方法没有将CRC计算为470f (它将其计算为DD7A)。

我希望有人能验证这段代码不能像供应商说的那样工作,或者帮助我让test_crc返回正确的值。

谢谢你的帮助。

EN

回答 3

Stack Overflow用户

发布于 2009-02-23 23:11:36

问题解决了。供应商提供的规格不正确。XYZ的正确校验和是DD7A。文档不正确。

此外,在之前的页面上,当他们解释要传递给calc_crc方法的数据以获得实际消息的crc时,这也是不正确的,这使得它成为一个棘手的项目。

谢谢你的帮助。

票数 4
EN

Stack Overflow用户

发布于 2009-02-23 15:09:21

计算,就像它进行的那样,没有显示任何我想到的错误。只需再次回顾算法即可。特别是,在查找可能的问题时,请注意在算法的不同部分进行and运算的常量是0x0fff0xffff。也许应该让0x0fff0xfff0更加对称……有时我们认为真正的问题可能来自另一个地方,而忘记仔细检查显而易见的事情……:)

票数 3
EN

Stack Overflow用户

发布于 2009-02-23 14:30:51

硬件平台是否相同?会不会是你的endianness不一样?(例如,您有x86,它们有68000个cpu。)

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/577787

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档