How do I use the bitwise operator XOR in Lua?

后端 未结 6 856
一向
一向 2020-12-30 05:38

How can I implement bitwise operators in Lua language?
Specifically, I need a XOR operator/method.

6条回答
  •  一生所求
    2020-12-30 05:56

    Since you're referencing the floor function 3 times, using an excessive number of loops for most operations (numbers less than 2^31 don't need all 31 loops), are using the ^ operator, and aren't capitalizing on the fact that a and b might be wildly different numbers with different magnitudes, you're losing a lot of efficiency. The function also isn't localized, and you're doing two more division operations than you need to. I wrote this to be reasonably fast.

    In general, you're going to see improvements of about 3 to 20 times.

    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 a0 do
            local ra=a%2
            if ra>0 then c=c+p end
            a,p=(a-ra)/2,p*2
        end
        return c
    end
    

    If you need more than this, say AND, OR, and NOT, then I've got you covered there, too.

    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
    

    Don't worry, you won't need to change anything.

提交回复
热议问题