Hi Admin,
Thank you, the checksum function works. I am trying to do the reverse and verify the message received has a valid checksum
The reversechk function does not return a 0, what am doing wrong? I have the reverse calculation in C code, maybe you can understand what they doing?
Thanks,
Roger
Thank you, the checksum function works. I am trying to do the reverse and verify the message received has a valid checksum
Code:
function checksum(str)
local sum = 0
for i = 1, #str do
sum = (sum + string.byte(str,i)) % 256
end
x = 256-sum
return string.format('%02X', 256 - sum)
end
function reversechk(str, cksum)
local sum = tonumber(cksum,16)
log(sum)
for i=1, #str do
sum= (sum + string.byte(str,i))
end
return string.format('%02X', sum)
end
local message= '16XK403923611081711000'
local chksum = checksum(message)
log(chksum)
-- chksum is 67
-- so the total message is '16XK40392361108171100067'
local isok = reversechk(message,chksum)
log(isok)
The reversechk function does not return a 0, what am doing wrong? I have the reverse calculation in C code, maybe you can understand what they doing?
Code:
Calculate checksum on received and transmitted ASCII string
Example C code program
//INT8U is an 8 bit unsigned integer.
INT8U itAscRecBuf[82]; //ASCII receive character buffer
INT8U AscHexToBin(INT8U, INT8U *); //ASCII hex to binary conversion
INT8U AsciiToHex( INT8U); //Ascii to Hex conversion
//Calculate checksum on a received ASCII string, return checksum value.
//It should equal 0 if good.
INT8U CalcCheckSum(void)
{
INT8U i,length, cc;
length = AscHexToBin(2, &itAscRecBuf[0]);
//get length value, first two characters
cc = AscHexToBin(2, &itAscRecBuf[length]); //get checksum value at end of string.
for (i=0;i<length ;i++ )
{
cc += itAscRecBuf[i]; //get string value and add it to checksum
}
return(cc);
//good checksum should equal 0 }
//ascii hex to binary, width 1 or 2
INT8U AscHexToBin(INT8U Width, INT8U * DataPtr) //
{
INT8U aVal; // accumulated value
aVal = AsciiToHex(*DataPtr);
DataPtr++;
if (Width == 2) //two digits wide, else 1 digit wide
{
aVal = aVal << 4;
aVal += AsciiToHex(*DataPtr);
}
return(aVal);
}
//Ascii to Hex conversion
INT8U AsciiToHex( INT8U Value )
{
switch ( Value )
{
case 'A': return( 10 );
case 'B': return( 11 );
case 'C': return( 12 );
case 'D': return( 13 );
case 'E': return( 14 );
case 'F': return( 15 );
default: return( Value - 0x30 );
}
}
Thanks,
Roger