What is error detection code?

Error detection codes such as Hamming, parity, LRC, checksum and CRC are codes added to the main data to let us detect any kind of error.

Imagine that we want to send some data to a receiver.

In order for the recipient to make sure that the delivered data is correct, an extra detection code attached to data (redundancy) needs to be sent.

The recipient calculates the error detection code based on the received data and then compares it with the actual received detection code.

If both are equal, the received data is correct.

**Error detection
using checksum**

checksum is used in many applications such as tcp header or ip header.

In this method we need to add the data up.

For example imagine we want to calculate the checksum 8bit. In order to do so we split the data into 8-bit sections and then add up those sections.

In general, the result will be more than 8 bits. If this happens, we should split the result again into 8-bit sections again and continue till we get an 8-bit result.

We should get the two’s compliment of this result. And the outcome will be the final checksum.

**Example **

0x56FE96A is split into these parts: 6A, E9, 6F and 5. The summation of these parts is 0x1C7, which is more than 8 bits. So we split it again into two other 8-bit parts: C7 and 1 and then sum up these last two again which gives us 0xC8 and its two’s complement is 0x38.

example code for calculation of 16bit checksum in the c language:

typedef unsigned char u8; typedef unsigned short u16; typedef unsigned int u32; u16 CalcChecksum(u8 *data, u16 Count) { u32 Sum = 0; while (Count > 1) { Sum += *data++; Count --; } while (Sum >> 16) //fold 32-bit sum to 16 bits { Sum = (Sum & 0xFFFF) + (Sum >> 16); } return ~Sum; }

author:M.R. Beygi

translator: F. Mirabbasi