Lua中的"按位与"

Fus*_*ieb 5 lua bit-manipulation operators

我正在尝试将代码从C转换为Lua,我遇到了问题.如何在Lua中翻译按位AND?源代码包含:

if((command&0x80)== 0)...

怎么能在Lua做到这一点?

我正在使用Lua 5.1.4-8

rya*_*son 5

这是纯 Lua 5.1 中一个基本的、隔离的按位与实现:

function bitand(a, b)
    local result = 0
    local bitval = 1
    while a > 0 and b > 0 do
      if a % 2 == 1 and b % 2 == 1 then -- test the rightmost bits
          result = result + bitval      -- set the current bit
      end
      bitval = bitval * 2 -- shift left
      a = math.floor(a/2) -- shift right
      b = math.floor(b/2)
    end
    return result
end
Run Code Online (Sandbox Code Playgroud)

用法:

print(bitand(tonumber("1101", 2), tonumber("1001", 2))) -- prints 9 (1001)
Run Code Online (Sandbox Code Playgroud)


Ego*_*off 5

OR, XOR, AND = 1, 3, 4

function bitoper(a, b, oper)
   local r, m, s = 0, 2^52
   repeat
      s,a,b = a+b+m, a%m, b%m
      r,m = r + m*oper%(s-a-b), m/2
   until m < 1
   return r
end

print(bitoper(6,3,OR))   --> 7
print(bitoper(6,3,XOR))  --> 5
print(bitoper(6,3,AND))  --> 2
Run Code Online (Sandbox Code Playgroud)