Tre*_*or 11 lua bitwise-operators logical-operators
如何在Lua语言中实现按位运算符?
具体来说,我需要一个XOR运算符/方法.
如果你曾经在Lua处理逻辑操作,我们很乐意听到.
[求助] - 这是我用过的:
__PRE__
Yu *_*Hao 18
在Lua 5.2中,您可以使用bit32库中的函数.
在Lua 5.3中,bit32库已经过时,因为现在存在本机按位运算符.
print(3 & 5) -- bitwise and
print(3 | 5) -- bitwise or
print(3 ~ 5) -- bitwise xor
print(7 >> 1) -- bitwise right shift
print(7 << 1) -- bitwise left shift
print(~7) -- bitwise not
Run Code Online (Sandbox Code Playgroud)
输出:
1
7
6
3
14
-8
Run Code Online (Sandbox Code Playgroud)
由于您引用了3次楼层函数,对于大多数操作使用过多的循环(小于2 ^ 31的数字不需要所有31个循环),正在使用^运算符,并且没有利用事实a和b可能是不同数量的不同数字,你会失去很多效率.该功能也没有本地化,你正在进行两次以上的除法运算.我写这篇文章的速度相当快.
一般来说,你会看到大约3到20倍的改进.
local function BitXOR(a,b)--Bitwise xor
local p,c=1,0
while a>0 and b>0 do
local ra,rb=a%2,b%2
if ra~=rb then c=c+p end
a,b,p=(a-ra)/2,(b-rb)/2,p*2
end
if a<b then a=b end
while a>0 do
local ra=a%2
if ra>0 then c=c+p end
a,p=(a-ra)/2,p*2
end
return c
end
Run Code Online (Sandbox Code Playgroud)
如果您需要更多,请说AND,OR和NOT,那么我也让你在那里.
local function BitOR(a,b)--Bitwise or
local p,c=1,0
while a+b>0 do
local ra,rb=a%2,b%2
if ra+rb>0 then c=c+p end
a,b,p=(a-ra)/2,(b-rb)/2,p*2
end
return c
end
local function BitNOT(n)
local p,c=1,0
while n>0 do
local r=n%2
if r<1 then c=c+p end
n,p=(n-r)/2,p*2
end
return c
end
local function BitAND(a,b)--Bitwise and
local p,c=1,0
while a>0 and b>0 do
local ra,rb=a%2,b%2
if ra+rb>1 then c=c+p end
a,b,p=(a-ra)/2,(b-rb)/2,p*2
end
return c
end
Run Code Online (Sandbox Code Playgroud)
别担心,你不需要改变任何东西.
如果您需要一种有效的方式进行按位移位,我不久前写了一篇关于此的文章。下面是一些封装技术的函数:
function lshift(x, by)
return x * 2 ^ by
end
function rshift(x, by)
return math.floor(x / 2 ^ by)
end
Run Code Online (Sandbox Code Playgroud)