lua 5.1 位运算

--[[
    位运算
    --与   同为1,则为1
    --或   有一个为1,则为1
    --truefalse,其余为true
    --异或 相同为0,不同为1
]]


local MathBit = {}


function MathBit.__andBit(left,right)    --return (left == 1 and right == 1) and 1 or 0
end

function MathBit.__orBit(left, right)    --return (left == 1 or right == 1) and 1 or 0
end

function MathBit.__xorBit(left, right)   --异或
    return (left + right) == 1 and 1 or 0
end

function MathBit.__base(left, right, op) --对每一位进行op运算,然后将值返回
    if left < right then
        left, right = right, left
    end
    local res = 0
    local shift = 1
    while left ~= 0 do
        local ra = left % 2    --取得每一位(最右边)
        local rb = right % 2
        res = shift * op(ra,rb) + res
        shift = shift * 2
        left = math.modf( left / 2)  --右移
        right = math.modf( right / 2)
    end
    return res
end


function MathBit:andOp(left, right)
    return MathBit.__base(left, right, MathBit.__andBit)
end

function MathBit:xorOp(left, right)
    return MathBit.__base(left, right, MathBit.__xorBit)
end

function MathBit:orOp(left, right)
    return MathBit.__base(left, right, MathBit.__orBit)
end

function MathBit:notOp(left)
    return left > 0 and -(left + 1) or -left - 1
end

function MathBit:lShiftOp(left, num)  --left左移num位
    if left < 0 then
        left = 2 ^ 32 + left
    end
    return left * (2 ^ num)
end

function MathBit:rShiftOp(left,num)  --right右移num位
    if left < 0 then
        left = 2 ^ 32 + left
    end
    return math.floor(left / (2 ^ num))
end

return MathBit
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值