How to calculate CRC 8 Check-Sum using C#.

Allemahesh
Posted by in C# category on for Beginner level | Points: 250 | Views : 9852 red flag

How to calculate CRC 8 Check-Sum using C# code.

Introduction


We are going to check the code that will calculate CRC 8 Check Sum of Hex Data.

Using the code

We are going to look into ComputeAdditionChecksum() function. This function will take the data bytes. Then these data bytes are then processed one at a time and CRC 8 will be calculated.

Below is the code:
public static byte ComputeAdditionChecksum(byte[] data)
{
    byte sum = 0;
    unchecked // Let overflow occur without exceptions
    {
        foreach (byte b in data)
        {
            sum += b;
        }
    }
    return sum;
}
Below is the code for UI. Here text box is used to get the hex data form the user. The entered data by user will be stored in byte array using for loop. After that byte array is passed to ComputeAdditionChecksum() function. 

Here is the code.
protected void btnSybmit_Click(object sender, EventArgs e)
{
    try
    {
        if (txtData.Text.Length % 2 == 0)
        {
            byte[] _crcdata = new byte[txtData.Text.Length / 2];
            int k = 0;
            for (int i = 0; i < txtData.Text.Length; i = i + 2)
            {
                _crcdata[k] = byte.Parse(txtData.Text.Substring(i, 2).ToString(), System.Globalization.NumberStyles.AllowHexSpecifier);
                k++;
            }
            byte _checkSumData = Crc8.ComputeAdditionChecksum(_crcdata);
            lblMsg.Text = Convert.ToString(_checkSumData);
        }
        else
            lblMsg.Text = "Invalid checksum data.";
    }
    catch
    {
        lblMsg.Text = "Invalid checksum data.";
    }
}

Demo





Conclusion

Hope you will enjoy this article. Please provide the suggestions on this article in comments section.

Page copy protected against web site content infringement by Copyscape

About the Author

Allemahesh
Full Name: MAHESH ALLE
Member Level: Silver
Member Status: Member,MVP
Member Since: 4/2/2012 1:34:42 AM
Country: India



Login to vote for this post.

Comments or Responses

Posted by: Anthonyzz on: 9/5/2013 | Points: 25
Because CRC is HashAlgorithm after all, so, if you want to calculate CRC 8 using c#http://www.keepautomation.com/how_to/csharp/ , you can derive your classes from System.Security.Cryptography.HashAlgorithm class.
Collapse | Copy Code
public class CRC16 : HashAlgorithm {
public class CRC32 : HashAlgorithm {
Then, upon first creation we'll generate hashtables with CRC values to enhance future performance. It’s all about values table for bytes from 0 to 255 , so we should calculate it only once and then we can use it statically.
Posted by: Coursedloadr on: 9/7/2013 | Points: 25
Nice article

Login to post response

Comment using Facebook(Author doesn't get notification)