# 141-c-sharp-crc-computation

Reading Time: 2 minutes

CRC computation is the method for error detection in sending/receiving binary data. It is different from error auto correction, but is much simpler in the implementation. The idea is to treat complete binary message as extremely large number. This number is then divided with specially chosen divisor and remainder is added to initial message. Division with carefully chosen divisor has it’s purpose. If divisor was arbitrary, division would be time demanding, and not so practical. However, if divisor is according to given communication standard such as

• CRC-16-ANSI (Polynomial X16+X15+X2+1)

or

• CRC-CCITT (Polynomial X16+X12+X5+1)

then no dividing is needed. Whole process of remainder calculus can be implemented in finite algebra with manipulation with bits. Point is to use integers as shift registers together with ex-or logic operation to produce remainder i.e. crc bytes.

Feedback coefficient depends on CRC polynomial, communication standard and if first bit in manipulation is most significant bit (MSB) or least significant bit (LSB), and if bits are taken in reverse or normal order:

• CRC-16-ANSI LSB-reverse (with 0xA001 coefficient)
• CRC-16-ANSI MSB-normal (with 0x8005 coefficient)
• CRC-XMODEM LSB-reverse (with 0x8408 coefficient)
• CRC-CCITT MSB-normal (with 0x1021 coefficient)

Now, core code is simple, and depending on standard, coefficient has to be set (0xA001, 0x8005, 0x8408 or 0x1021). Initial value of the shift register has to be set on 0x0000 or 0xFFFF.

public void crc_bytes(int[] int_input)
{

int_array = int_input;
int int_crc = 0x0; // or 0xFFFF;

int int_lsb;
for (int int_i = 0; int_i < int_array.Length; int_i++)
{

int_crc = int_crc ^ int_array[int_i];
for (int int_j = 0; int_j < 8; int_j ++ )
{

int_lsb = int_crc & 0x0001; // Mask of LSB
int_crc = int_crc >> 1;
int_crc = int_crc & 0x7FFF;
if (int_lsb == 1) int_crc = int_crc ^ 0x8408;

}

}
int_crc_byte_a = int_crc & 0x00FF;
int_crc_byte_b = (int_crc >> 8) & 0x00FF;

}