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

由於lua5.1不支持位操作,自己寫了一個lua的位操作函數,代碼如下:

方法1:


function Xor(num1,num2)
	local tmp1 = num1
	local tmp2 = num2
	local str = ""
	repeat
		local s1 = tmp1 % 2
		local s2 = tmp2 % 2
		if s1 == s2 then
			str = "0"..str
		else
			str = "1"..str
		end
		tmp1 = math.modf(tmp1/2)
		tmp2 = math.modf(tmp2/2)
	until(tmp1 == 0 and tmp2 == 0)
	return tonumber(str,2)
end

function And(num1,num2)
	local tmp1 = num1
	local tmp2 = num2
	local str = ""
	repeat
		local s1 = tmp1 % 2
		local s2 = tmp2 % 2
		if s1 == s2 then
			if s1 == 1 then
				str = "1"..str
			else
				str = "0"..str
			end
		else
			str = "0"..str
		end
		tmp1 = math.modf(tmp1/2)
		tmp2 = math.modf(tmp2/2)
	until(tmp1 == 0 and tmp2 == 0)
	return tonumber(str,2)
end

function Or(num1,num2)
	local tmp1 = num1
	local tmp2 = num2
	local str = ""
	repeat 
		local s1 = tmp1 % 2
		local s2 = tmp2 % 2
		if s1 == s2 then
			if s1 == 0 then
				str = "0"..str
			else
				str = "1"..str
			end
		else
			str = "1"..str
		end
		tmp1 = math.modf(tmp1/2)
		tmp2 = math.modf(tmp2/2)
	until(tmp1 == 0 and tmp2 == 0)
	return tonumber(str,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 的操作結果

加入支持負數的位運算操作: 但是負數和負數位操作出來的顯示是個整數

如 And(-8,-5)    結果 :4294967288  在32位機器上就是 -8

function checkNums( nums )
	local n = nums
	if n >= 0 then
		return n
	else
		n = 0 - n
		n = 0xffffffff - n + 1
	end
	return n
end
function resultCover( n )
	local  num = n
	if num >= 0x80000000 then
		num = num - 0xffffffff - 1
	end
	return num
end

function And(num1,num2)
	local tmp1 = checkNums(num1)
	local tmp2 = checkNums(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 resultCover(ret)
end

function Or(num1,num2)
	local tmp1 = checkNums(num1)
	local tmp2 = checkNums(num2)
	local ret = 0
	local count = 0
	repeat
		local s1 = tmp1 % 2
		local s2 = tmp2 % 2
		if s1 == s2 and s1 == 0 then

		else
			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 resultCover(ret)
end


function Xor(num1,num2)
	local tmp1 = checkNums(num1)
	local tmp2 = checkNums(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 resultCover(ret)
end

5.3開始自帶位操作:

&	按位與
|	按位或
~	按位異或
>>	右移
<<	左移
~	按位非

使用方法:
c = a & b      
c = a | b
c = a ~ b
c = a >> b
c = a << b
c = ~a

 

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