How do I use the bitwise XOR operator in Lua?

How can I implement bitwise operators in Lua?
In particular, I need an XOR statement / method.

+10
source share
6 answers

In Lua 5.2 you can use bit32library functions bit32.

In Lua 5.3, the library is bit32deprecated because it now has its own bitwise operators .

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

Output:

1
7
6
3
14
-8
+16
source

In Lua 5.2 you can use a function bit32.bxor.

+11
source

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

, , "", "" "", .

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

, - .

+7

, . , :

function lshift(x, by)
  return x * 2 ^ by
end

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



. NAND. https://en.wikipedia.org/wiki/NAND_logic

function xor(a,b)
    return not( not( a and not( a and b ) ) and not( b and not( a and b ) ) )
end

1,0 ,

    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

, -.

0

; .


XOR 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
0

All Articles