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