views:

150

answers:

3

I'm sending a byte array to a piece of hardware.

The first 7 bytes contain data and the 8th byte is a checksum.

The 8th byte is the Least Significant Byte of the sum of the first 7 bytes.

Examples that include the correct checksum. The last byte of each of these is the checksum

200-30-7-5-1-2-0-245

42-0-0-1-176-0-148-39

42-0-0-3-177-0-201-118

How do I calculate the checksum?

Thanks, Seth

+1  A: 

Same as in C: take the sum and 'bitwise and' it with 255 (or 0xff in hexadecimal). Using your first set of data as an example:

arr = [ 200, 30, 7, 5, 1, 2, 0 ]

sum = 0
arr.each do |val|
    sum += val
end
checksum = sum & 0xff

print checksum
Michael Burr
thanks for the quick reply. I tried your method with the 2nd and 3rd data sets and it gives me an answer different than the checksum included in the examples. Anything I'm missing?
Seth Archer
The only things I can think of are that either the checksum is something different than just adding up the values modulo 256 or that the data set examples are wrong. Trying the calculations by hand matches the program snippet (ie., the 2nd and 3rd data sets don't work out).
Michael Burr
I've figured out most of what was wrong. The documentation is poor, but it seems that commands that start with 42 are for all devices on the network and do not have params that change so the checksum on the last 2 data sets is provided and not computed the same as the first.
Seth Archer
By the way do you a bitwise operation to find the most significant byte?
Seth Archer
+1  A: 

String objects have a number of methods for direct byte manipulation.

Azeem.Butt
+1  A: 

A short way to write it would be

arr.inject { |sum, val| sum += val } & 0xFF

But as previously discovered, this produces a different checksum for your second and third examples. It looks as though either the examples are incorrect or the checksum calculation is not as simple as taking the least significant byte.

Arkku