CRC-4 implementation in C#

匿名 (未验证) 提交于 2019-12-03 02:16:02

问题:

I've been searching the net for a C# implementation of the 4-bit cyclic redundancy check (CRC-4-ITU) but so far I've been unsuccessful.

Is there anyone who's able to give me a reference implementation of CRC-4-ITU? Preferrably with the standard polynomial if there is a standard polynomial (I've read the spec pointed to by wikipedia as the CRC4 spec without finding a definition of the polynomial).

I'd also really appreciate some sort of test suite or test data to verify a CRC4 implementation.

Thanks!

回答1:

The Cyclic Redundancy Check article at Wikipedia says the polynomial is x^4 + x + 1. There is also a pretty good description of how the checksum is computed.

Here is an algorithm for CRC16. I know it's not what you asked for, but it should be relatively straightforward to adapt it for 4 bits.

   public ushort calculate(byte[] bytes)     {         int crc = 0xFFFF; // initial value         // loop, calculating CRC for each byte of the string         for (int byteIndex = 0; byteIndex < bytes.Length; byteIndex++)         {             ushort bit = 0x80; // initialize bit currently being tested             for (int bitIndex = 0; bitIndex < 8; bitIndex++)             {                 bool xorFlag = ((crc & 0x8000) == 0x8000);                 crc <<= 1;                 if (((bytes[byteIndex] & bit) ^ (ushort)0xff) != (ushort)0xff)                 {                     crc = crc + 1;                 }                 if (xorFlag)                 {                     crc = crc ^ 0x1021;                 }                 bit >>= 1;             }         }         return (ushort)crc;     } 

http://www.experts-exchange.com/Programming/Languages/C_Sharp/Q_24775723.html

Also, there is this guide to computing checksums:

http://www.ross.net/crc/download/crc_v3.txt

"Everything you wanted to know about CRC algorithms, but were afraid to ask for fear that errors in your understanding might be detected."



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!