Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calculate two's complement checksum of hexadecimal string

I have a string "0AAE0000463130004144430000" and I need to calculate the two's complement checksum of the hex bytes that make up the string.

The formula for the example string above is

  1. Sum the values: 0A + AE + 00 + 00 + 46 + 31 + 30 + 00 + 41 + 44 + 43 + 00 + 00 = 27 (discard the overflow)
  2. Subtract the result from 0x100 = 0xD9

D9 is the correct checksum for this example, but I am having trouble getting the two digit hex values parsed out of the string in C#. My current code is below:

string output = "0AAE0000463130004144430000";
long checksum = 0;
char[] outputBytes = output.TrimStart(':').ToCharArray();

foreach (var outputByte in outputBytes)
{
    checksum += Convert.ToInt32(outputByte);
    checksum = checksum & 0xFF;
}

checksum = 256 - checksum;

However, this is summing the ASCII values as far as I can tell, and doing it for each individual character.

like image 922
Crake Avatar asked Dec 11 '22 21:12

Crake


2 Answers

You can use SoapHexBinary class in System.Runtime.Remoting.Metadata.W3cXsd2001.

soapHexBinary.Value property will return you a byte array

string hexString = "0AAE0000463130004144430000";
byte[] buf = SoapHexBinary.Parse(hexString).Value;

int chkSum = buf.Aggregate(0, (s, b) => s += b) & 0xff;
chkSum = (0x100 - chkSum) & 0xff;

var str = chkSum.ToString("X2"); // <-- D9
like image 200
L.B Avatar answered Dec 14 '22 11:12

L.B


Try this instead. Grab two characters at a time using SubString, and read the pair of characters as a hex value using int.Parse with NumberStyles.AllowHexSpecifier.

string output = "0AAE0000463130004144430000";
int checksum = 0;

// You'll need to add error checking that the string only contains [0-9A-F], 
// is an even number of characters, etc.
for(int i = 0; i < output.length; i+=2)
{
   int value = int.Parse(output.SubString(i, 2), NumberStyles.AllowHexSpecifier);
   checksum = (checksum + value) & 0xFF;
}

checksum = 256 - checksum;
like image 26
David Yaw Avatar answered Dec 14 '22 11:12

David Yaw