09-08-2017 11:05 AM - edited 09-08-2017 11:22 AM
*****
UPDATE: Problem was resolved by changing sendBytes from char to unsigned char. I would still like to know why the CheckSum addition would drop 256 when adding a char value of 136 which is actually stored as -110 or something similar.
*****
I am trying to do a checksum calculation and someone very odd is happening. This message is adding a parameter list by name to a server. The more parameters I add, the larger the messed. When I add 26 it works. When I go to 27 it fails the CheckSum. I ran the same code in VB and it worked so I output the CheckSum value at each calculation interval and this POS is dropping the first byte's contribution of 256.
My first code kept the entire calculation on one line with a += operator. As I noticed the error I broke it down into smaller chunks. It exibits the same behavior. The first two values of the array are 1 and 136. In the first iteration of the loop below CheckSum will be 256 on line 3. Then after running line 4 it DELETES the 256 and sets CheckSum to 136. Every future iteration calculates correctly and the difference at the end of an almost 3.9 million summation is precisely 256. To further baffle me, I removed one named parameter from the list to determine the difference. The first value is sendBytes is 1, and the second is 118. In this case it DOES NOT drop the 1 * 256 = 256!!!!. Just to make sure you guys believe me I have added a sequence of screen shots tracing through execution. Why is this happening?
for (Count = 0; Count < (IndexCount / 2); Count++) { CheckSum = CheckSum + (sendBytes[Count * 2] * 256); CheckSum = CheckSum + (sendBytes[Count * 2 + 1]); DebugPrintf("%ld\r\n", CheckSum); }
Solved! Go to Solution.
09-08-2017 01:54 PM - edited 09-08-2017 02:08 PM
I can no longer edit the post, but we also determined this:
256 is the complement to a negative number and the math always ends up equaling the second number... I'll by using unsigned char for my byte arrays moving forward...
Byte[0] = 1
Byte[1] = 0x88 or -120 or 136
Byte[0] * 256 + Byte[1] = 136
256 + -120 = 136