CRC-4 implementation in C#
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."
Markus Olsson
Developer at GitHub. Working on GitHub Desktop and other fun projects
Updated on June 04, 2022Comments
-
Markus Olsson almost 2 years
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!