I have packet data, which I am storing as a public static List<byte> packet = new List<byte>();
The last byte of this is a checksum, and I am trying to figure out how to use this to check the packet data.
When I have a full packet, I run:
//get checksum
byte chcksm = packet[packet.Count - 1];
int sum = chcksm;
to get the value of the checksum byte.
Then I run:
//checksum calculation
public static byte ComputeAdditionChecksum(List<byte> data)
{
byte sum = 0;
unchecked // Let overflow occur without exceptions
{
foreach (byte b in data)
{
sum += b;
}
}
return sum;
}
on packet
to get the value of the whole packet, and save it in an int called packetSum
.
Comparing these two vales, on a test packet,packetSum
, the value of the whole packet, returns 76
. And the value of the checksum byte returns 103.
Am I doing this wrong?
//edit, in thedocs, it says this about the checksum..
1 Byte checksum expressed as:
unsigned char CalcChkSum(unsigned char *MsgBlock,
int Length)
{
unsigned char Total = 0x40;
int i;
for (i = 0; i < Length-1; i++)
{
Total -= MsgBlock[i];
}
return Total;
}
It looks like you're including the checksum in your calculation. Without seeing the underlying data with expected and actual results I'd say changing the loop as follows should fix the issue:
public static byte ComputeAdditionChecksum(List<byte> data)
{
byte sum = 0x40;
unchecked // Let overflow occur without exceptions
{
for (var i = 0; i < data.Count - 1; i++)
{
sum -= data[i];
}
}
return sum;
}