校验和计算
为了计算 CRC,我找到了一段代码,但我不理解这个概念。 这是代码:
count =128 and ptr=some value;
calcrc(unsigned char *ptr, int count)
{
unsigned short crc;
unsigned char i;
crc = 0;
while (--count >= 0)
{
crc = crc ^ (unsigned short)*ptr++ << 8;
i = 8;
do
{
if (crc & 0x8000)
crc = crc << 1 ^ 0x1021;
else
crc = crc << 1;
} while(--i);
}
return (crc);
}
请任何人解释并告诉我逻辑。
To calculate CRC I found a piece of code but I am not understanding the concept.
Here is the code:
count =128 and ptr=some value;
calcrc(unsigned char *ptr, int count) { unsigned short crc; unsigned char i; crc = 0; while (--count >= 0) { crc = crc ^ (unsigned short)*ptr++ << 8; i = 8; do { if (crc & 0x8000) crc = crc << 1 ^ 0x1021; else crc = crc << 1; } while(--i); } return (crc); }
Please any body explain and tell me the logic.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
这看起来像一个 CRC (具体来说,它看起来像 CRC-16-CCITT,被诸如802.15.4、X.25、V.41、CDMA、蓝牙、XMODEM、HDLC、PPP 和 IrDA)。 您可能想在链接到的维基百科页面上阅读 CRC 理论,以获得更多见解。 或者您可以将其视为仅解决计算校验和问题的“黑匣子”。
This looks like a CRC (specifically it looks like CRC-16-CCITT, used by things like 802.15.4, X.25, V.41, CDMA, Bluetooth, XMODEM, HDLC, PPP and IrDA). You might want to read up on the CRC theory on the linked-to Wikipedia page, to gain some more insight. Or you can view this as a "black box" that just solves the problem of computing a checksum.
您可能需要知道,在 C 中,^ 运算符是按位异或运算符, << 运算符是左移运算符(相当于乘以运算符右侧数字的 2 次方)。 还有 crc 和 0x8000 表达式正在测试变量 crc 的最高有效位集。
这将帮助您对运行时发生的情况进行低级解释,有关 CRC 是什么以及您可能需要它的原因的高级解释,请阅读 维基百科页面 或 工作原理。
You will probably need to know that in C, the ^ operator is a bitwise XOR operator and the << operator is the left shift operator (equivalent to multiplication by 2 to the power of the number on the right of the operator). Also the crc & 0x8000 expression is testing for the most significant bit set of the variable crc.
This will help you to work out a low level explanation of what is occurring when this runs, for a high level explanation of what a CRC is and why you might need it, read the Wikipedia page or How Stuff Works.
关于 CRC 的一篇著名文章是 Ross 的“CRC 错误检测算法无痛指南”威廉姆斯. 吸收需要一些时间,但相当彻底。
One famous text on CRCs is "A Painless Guide to CRC Error Detection Algorithms" by Ross Williams. It takes some time to absorb but it's pretty thorough.
看看我的回答
我如何猜测校验和算法?
Take a look at my answer to
How could I guess a checksum algorithm?