Friday, September 4, 2015

Generating XOR checksum in C#

Here is the code to generate the checksum


using System;
using System.Globalization;

public class Program
{
public static void Main()

//suman first convert to byte[]
byte[] bb = ConvertHexadecimalStringToByteArray("030100AA1902");
//calculate checksum with the above byte[]
Console.WriteLine(calculateCheckSum(bb));
}

//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;
}
}


check the fiddle: Fiddle Link