串口常用校验算法(累加和、异或和)
1、异或和
异或和就是对数据逐一异或计算(异或结果与下一个数据异或)
下面是校验实例
local rdbuf = "FFFF28000000000000600001000D0000000000000000000000000000000000000000000000000000000096" local fast = string.sub(rdbuf, 5, string.len(rdbuf)-2) local last = string.sub(rdbuf, string.len(rdbuf)-1, string.len(rdbuf)) local num = bit.bxor(tonumber(string.sub(fast, 1, 2), 16), tonumber(string.sub(fast, 3, 4), 16)) --异或 local length = string.len(fast) - 1 for i = 5, length, 2 do num = bit.bxor(num, tonumber(string.sub(fast, i, i+1), 16)) end if num == tonumber(last, 16) then
校验成功
end
2、累加和
累加和也是逐一累加,但是计算不进位,所以最终结果其实是累加结果求256的余数
下面是计算实例
local cmd = 10 cmd = string.format("%02X",cmd) -- 02X 是为了保留两位,空位置0 例如(A是0A) local fast = "18000000000000600001000200".. cmd .."00000000000000010006" local length = #fast - 1 local num = 0 for i = 1, length, 2 do num = num + tonumber(string.sub(fast, i, i+1), 16) end num = num % 256 num = string.format("%02X",num) local instruction = "FFFF" .. fast .. num print(instruction)