checksum Calculation

CSharp · Console

/Program.cs

using System;
using System.Globalization;

public class Program
{
	public static void Main()
	{
		//suman first convert to byte[]
		byte[] bb = ConvertHexadecimalStringToByteArray("030100AA1902");
		
		byte b = calculateCheckSum(bb);
			//myByte.ToString("X2")
		Console.WriteLine("returned checksum  byte= "+b);
		Console.WriteLine("returned checksum in Hexadecimal format= "+b.ToString("X2"));
	}

	//Following converts the hex to a byte[]
	public static byte[] ConvertHexadecimalStringToByteArray(string hexadecimalString)
	{
		if (hexadecimalString.Length % 2 != 0)
		{
			throw new ArgumentException(String.Format(CultureInfo.InvariantCulture, "HexaDecimal cannot have an odd number of digits: {0}", hexadecimalString));
		}

		byte[] hexByteArray = new byte[hexadecimalString.Length / 2];
		for (int index = 0; index < hexByteArray.Length; index++)
		{
			string byteValue = hexadecimalString.Substring(index * 2, 2);
			hexByteArray[index] = byte.Parse(byteValue, NumberStyles.HexNumber, CultureInfo.InvariantCulture);
		}

		return hexByteArray;
	}
	
    //calculates the checksum from the byte[] 
	private static byte calculateCheckSum(byte[] byteData)
	{
		Byte chkSumByte = 0x00;
		for (int i = 0; i < byteData.Length; i++)
			chkSumByte ^= byteData[i];
		return chkSumByte;
	}
}
;