用LUA脚本写的demo,大家可以参考
---
--- Generated by EmmyLua(https://github.com/EmmyLua)
--- Created by liuyu.
--- DateTime: 2022/1/27 16:17
---
function And(num1,num2)
local tmp1 = num1
local tmp2 = num2
local ret = 0
local count = 0
repeat
local s1 = tmp1 % 2
local s2 = tmp2 % 2
if s1 == s2 and s1 == 1 then
ret = ret + 2^count
end
tmp1 = math.modf(tmp1/2)
tmp2 = math.modf(tmp2/2)
count = count + 1
until(tmp1 == 0 and tmp2 == 0)
return ret
end
function Xor(num1,num2)
local tmp1 = num1
local tmp2 = num2
local ret = 0
local count = 0
repeat
local s1 = tmp1 % 2
local s2 = tmp2 % 2
if s1 ~= s2 then
ret = ret + 2^count
end
tmp1 = math.modf(tmp1/2)
tmp2 = math.modf(tmp2/2)
count = count + 1
until(tmp1 == 0 and tmp2 == 0)
return ret
end
function bit_rshift(value,n)
value = math.modf(value / (2^n))
return value
end
function CRC16(arr,len)
local tmp = 0xffff
for i=1,len do
tmp = Xor(arr[i],tmp)
for j=1,8 do
local tmp1 = And(tmp,0x01)
if tmp1 == 1 then
tmp = bit_rshift(tmp,1)
tmp = Xor(tmp,0xa001)
else
tmp = bit_rshift(tmp,1)
end
end
end
local ret1 = (tmp % 256)
local ret2 = math.modf( tmp / 256)
return ret1,ret2
end
requestADU = {}
requestADU[1] = 0x01
requestADU[2] = 0x03
requestADU[3] = 0x00
requestADU[4] = 0x00
requestADU[5] = 0x00
requestADU[6] = 0x01
crcH,crcL = CRC16(requestADU,6)
requestADU[7] = crcH
requestADU[8] = crcL
for i=1,8 do
print(string.format("%x",requestADU[i]))
end
所以整个是 01 03 00 00 00 01 84 0a
CRC是84 0a