Odd Checksum Result(s) - Not Receiving Expected Results

别等时光非礼了梦想. 提交于 2019-12-11 12:37:16

问题


I have been trying to produce a checksum based on a file header and am receiving conflicting results. In the slave devices manual, it states the following to produce the checksum:

"A simple eight-bit calculation is used for the header checksum. The steps required are as follows:

  1. Calculate the sum of the header bytes in a single byte. Alternatively calculate the sum and then AND the result with FFhex.
  2. The checksum = FFhex - the sum from step 1."

Here, I have created the following code in Lua:

function header_checksum(string)
    local sum = 0
    for i = 1, #string do
       sum = sum + string.byte(i)
    end
    local chksum = 255 - (sum & 255)
    return chksum
end

If I send the following (4x byte) string down print(header_checksum("0181B81800")) I get the following result:

  • 241 (string sent as you see it)
  • 0 (each byte is changed to hex and then sent to function)

In the example given, it states that the byte should be AD, which is 173(dec) or \255.

Can someone please tell me what is wrong with what I am doing; either the code written, my approach, or both?


回答1:


function header_checksum(header)
   local sum = -1
   for i = 1, #header do
      sum = sum - header:byte(i)
   end
   return sum % 256
end

print(header_checksum(string.char(0x01,0x81,0xB8,0x18,0x00))) --> 173


来源:https://stackoverflow.com/questions/34139593/odd-checksum-results-not-receiving-expected-results

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!