"Bitwise AND" 在 Lua

"Bitwise AND" in Lua

我正在尝试将代码从 C 翻译成 Lua,但我遇到了问题。 如何在 Lua 中翻译按位与? C源代码包含:

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

如何在 Lua 中完成?

我正在使用 Lua 5.1.4-8

这是纯 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

用法:

print(bitand(tonumber("1101", 2), tonumber("1001", 2))) -- prints 9 (1001)

Lua5.1 中非负 32 位整数的按位运算的实现

OR, XOR, AND = 1, 3, 4

function bitoper(a, b, oper)
   local r, m, s = 0, 2^31
   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

如果您使用 Adobe Lightroom Lua,Lightroom SDK 包含用于 "bitwise AND" 操作的 LrMath.bitAnd() 方法:

-- x = a AND b

local a = 11
local b = 6
local x  = import 'LrMath'.bitAnd(a, b)

-- x is 2

还有LrMath.bitOr(a, b)LrMath.bitXor(a, b)方法用于"bitwise OR"和"biwise XOR"操作。

这是一个示例,说明我如何按位和具有常量的值 0x8000:

result = (value % 65536) - (value % 32768)  -- bitwise and 0x8000

此答案专门针对 Lua 5.1.X

你可以使用

if( (bit.band(command,0x80)) == 0) then
...

在 Lua 5.3.X 之后就非常简单了...

print(5 & 6)

希望对您有所帮助