Lua在5.3版本之前没有进行位操作的运算符,如果想用一些位操作没有那么容易,可以使用BIt库来处理,这里分享几个使用纯Lua写的异或运算
local floor = math.floor
function bxor (a,b)
local r = 0
for i = 0, 31 do
local x = a / 2 + b / 2
if x ~= floor (x) then
r = r + 2^i
end
a = floor (a / 2)
b = floor (b / 2)
end
return r
end
function bin_xor(x, y)
local z = 0
for i = 0, 31 do
if (x % 2 == 0) then -- x had a '0' in bit i
if ( y % 2 == 1) then -- y had a '1' in bit i
y = y - 1
z = z + 2 ^ i -- set bit i of z to '1'
end
else -- x had a '1' in bit i
x = x - 1
if (y % 2 == 0) then -- y had a '0' in bit i
z = z + 2 ^ i -- set bit i of z to '1'
else
y = y - 1
end
end
y = y / 2
x = x / 2
end
return z
end
XOR_l =
{
{0,1},
{1,0},
}
function xor(a,b)
pow = 1
c = 0
while a > 0 or b > 0 do
c = c + (XOR_l[(a % 2)+1][(b % 2)+1] * pow)
a = math.floor(a/2)
b = math.floor(b/2)
pow = pow * 2
end
return c
end
都好使可以直接拿去用