奇校验和结果-未收到预期结果 [英] Odd Checksum Result(s) - Not Receiving Expected Results

查看:75
本文介绍了奇校验和结果-未收到预期结果的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在尝试基于文件头生成校验和,并且收到冲突的结果.在从属设备手册中,它声明了以下内容以产生校验和:

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. 计算单个字节中标头字节的总和.或者计算 总和,然后将结果与FFhex相加.
  2. 校验和= FFhex-步骤1的总和."
  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."

在这里,我已经在Lua中创建了以下代码:

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

如果向下发送以下(4x字节)字符串,则得到以下结果:

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

  • 241(按您所看到的方式发送的字符串)
  • 0(每个字节更改为十六进制,然后发送给函数)

在给出的示例中,它指出该字节应为AD,即173(dec)或\ 255.

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?

推荐答案

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

这篇关于奇校验和结果-未收到预期结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆