luabit-manipulationoperators

"Bitwise AND" in Lua


I'm trying to translate a code from C to Lua and I'm facing a problem. How can I translate a Bitwise AND in Lua? The source C code contains:

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

How can this be done in Lua?

I am using Lua 5.1.4-8


Solution

  • Here is a basic, isolated bitwise-and implementation in pure 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
    

    usage:

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