LUA 5.1 CRC16/Modbus 校驗 純LUA實現

導語:由於LUA5.1上,不支持位操作,先自實現了在 lua 5. 1 上的位操作

具體代碼如下:

1)調用CRC16函數即可,函數返回是 CRC16/MODBUS 校驗的校驗位

2)提供驗證代碼準確性的網站: http://www.ip33.com/crc.html

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)
	local tmp = 0xffff
	for i=1,#arr 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


--調用

arr[1] = 0x01
arr[2] = 0x03
arr[3] = 0x61
arr[4] = 0x00
arr[5] = 0x00
arr[6] = 0x02

print(CRC16(arr))

--輸出: 219	247  (DB F7)

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章