关于Lua:Lua – Bitwise Logical Operations

Lua - Bitwise Logical Operations

如何在Lua语言中实现按位运算符?
具体来说,我需要一个XOR运算符/方法。

如果你曾经在Lua处理逻辑操作,我们很乐意听到。

[求助] - 这是我用过的:

1
2
3
4
5
6
7
8
9
10
11
12
13
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

在Lua 5.2中,您可以使用bit32库中的函数。

在Lua 5.3中,bit32库已废弃,因为现在存在本机按位运算符。

1
2
3
4
5
6
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

输出:

1
2
3
4
5
6
1
7
6
3
14
-8

在Lua 5.2中,您可以使用bit32.bxor函数。


由于您引用了3次楼层函数,对于大多数操作使用过多的循环(小于2 ^ 31的数字不需要所有31个循环),正在使用^运算符,并且没有利用事实a和b可能是不同数量的不同数字,你会失去很多效率。该功能也没有本地化,你正在进行两次以上的除法运算。我写这篇文章的速度相当快。

一般来说,你会看到大约3到20倍的改进。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
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

如果您需要更多,请说AND,OR和NOT,那么我也让你在那里。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
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

别担心,你不需要改变任何东西。


如果您需要一种有效的方式来进行按位移位,我前一段时间就写了一篇文章。以下是一些包含该技术的函数:

1
2
3
4
5
6
7
function lshift(x, by)
  return x * 2 ^ by
end

function rshift(x, by)
  return math.floor(x / 2 ^ by)
end

这很简单。使用NAND逻辑。
https://en.wikipedia.org/wiki/NAND_logic

1
2
3
function xor(a,b)
    return not( not( a and not( a and b ) ) and not( b and not( a and b ) ) )
end

如果您还需要1,0个输入,请在功能中插入以下内容

1
2
    a = a==1 or a == true   -- to accept nil, 1, 0, true or false
    b = b==1 or b == true   -- to accept nil, 1, 0, true or false

希望这有助于某人。