Lua 位操作(與,或,異或操作)

由於事先不知道lua5.3才支持位操作,自己寫了一個lua的位操作函數,測試過了,沒有bug代碼如下:


function tobinary(num)
	local tmp = num
	local str = ""
	repeat
		if tmp % 2 == 1 then
			str = str.."1"
		else 
			str = str.."0"
		end
		tmp = math.modf(tmp/2)
	until(tmp == 0)
	str = string.reverse(str)
	return str
end

function makesamelength(num1,num2)
	local str1 = tobinary(num1)
	local str2 = tobinary(num2)
	local len1 = string.len(str1)
	local len2 = string.len(str2)
	local len = 0
	local x = 0
	if len1 > len2 then
		x = len1 - len2
		for i=1,x do
			str2 = "0"..str2
		end
		len = len1
	elseif len2 > len1 then
		x = len2 - len1
		for i=1,x do
			str1 = "0"..str1
		end
		len = len2
	end
	return str1,str2,len
end
function Xor(num1,num2)
	local str1 
	local str2 
	local len 
	local tmp = ""
	str1,str2,len = makesamelength(num1,num2)
	for i=1,len do
		local s1 = string.sub(str1,i,i)
		local s2 = string.sub(str2,i,i)
		if s1 == s2 then
			tmp = tmp.."0"
		else
			tmp = tmp.."1"
		end
	end
	--tmp = string.reverse(tmp)
	return tonumber(tmp,2)
end

function And(num1,num2)
	local str1 
	local str2 
	local len 
	local tmp = ""
	str1,str2,len = makesamelength(num1,num2)
	for i=1,len do
		local s1 = string.sub(str1,i,i)
		local s2 = string.sub(str2,i,i)
		if s1 == s2 then
			if s1 == "1" then
				tmp = tmp.."1"
			else
				tmp = tmp.."0"
			end
		else
			tmp = tmp.."0"
		end
	end
	--tmp = string.reverse(tmp)
	return tonumber(tmp,2)
end

function Or(num1,num2)
	local str1 
	local str2 
	local len 
	local tmp = ""
	str1,str2,len = makesamelength(num1,num2)
	for i=1,len do
		local s1 = string.sub(str1,i,i)
		local s2 = string.sub(str2,i,i)
		if s1 == s2 then
			if s1 == "0" then
				tmp = tmp.."0"
			else
				tmp = tmp.."1"
			end
		else
			tmp = tmp.."1"
		end
	end
	--tmp = string.reverse(tmp)
	return tonumber(tmp,2)
end

使用方法如下:

local tmp1 = 0x52
local tmp2 = 0x01

print(xor(tmp1,tmp2))  --輸出tmp1 異或 tmp2 的操作結果
print(And(tmp1,tmp2))    --輸出tmp1 與 tmp2 的操作結果
print(Or(tmp1,tmp2))    --輸出tmp1 或 tmp2 的操作結果

 

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