'Program logic to calculate hexacode checksum?
I have a hexadecimal code for which I have to perform a checksum logic which will give me a checksum that will be added to the end of the Hexacode message and passed to the receiving TCP server and after that, the message I received from the server needs to be checked by performing checksum logic
Eg: I have a hexacode of 07040A13 for which checksum value is coming 58 which is added and passed as 07040A1358. In receiving I am getting 25000A01F0FFFFFFFF for this the checksum value is 64 and whole message is 25000A01F0FFFFFFFF64 The sum of this value should be 0 and the logic for checksum is (80 + Message)NOT+1 = Checksum value And (80 + Message)Not +1 + Checksum = 0
I want this logic to be performed in C# code but I do not know where and how to start.
I have got one working solution but it is in javascript:
function calculate_checksum8(N)
{
// convert input value to upper case
strN = new String(N);
strN = strN.toUpperCase();
strHex = new String("0123456789ABCDEF");
result = 0;
fctr = 16;
for (i=0; i<strN.length; i++)
{
if (strN.charAt(i) == " ") continue;
v = strHex.indexOf(strN.charAt(i));
if (v < 0)
{
result = -1;
break;
}
result += v * fctr;
if (fctr == 16)
fctr = 1;
else
fctr = 16;
}
if (result < 0)
{
strResult = new String("Non-hex character entered");
}
else if (fctr == 1)
{
strResult = new String("Odd number of characters entered. e.g. correct value = aa aa");
}
else
{
// Calculate 2's complement
result = (~(result & 0xff) + 1) & 0xFF;
// Convert result to string
strResult = strHex.charAt(Math.floor(result/16)) + strHex.charAt(result%16);
}
return strResult;
}
Solution 1:[1]
public string CreateCheckSum(string hex)
{
string withchk = "80" + hex;
string strres = "";
string strHex = "0123456789ABCDEF";
int res = 0;
int fctr = 16;
for (int i = 0; i < withchk.Length; i++)
{
if (withchk[i] == ' ')
continue;
var v = strHex.IndexOf(withchk[i]);
if (v < 0)
{
res = -1;
break;
}
res += v * fctr;
if (fctr == 16)
fctr = 1;
else
fctr = 16;
}
if (res < 0)
return "Invalid";
else if (fctr == 1)
return "Invalid";
else
{
res = (~(res & 0xff) + 1) & 0xFF;
strres = strHex[(int)Math.Floor(res / 16.0)].ToString() + strHex[res % 16].ToString();
}
return strres;
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Shalabh Mishra |