Reputation: 1374
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
Upvotes: 10
Views: 26917
Reputation: 23727
Implementation of bitwise operations in Lua 5.1 for non-negative 32-bit integers
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
P.S.
Lua 5.1 also has non-standard (external) library written in C: require"bit"; x=bit.band(y,z)
Lua 5.2 has standard bit32
library for bitwise functions: x=bit32.band(y,z)
Lua 5.3+ has int64 datatype with native bitwise operators: x=y&z
Upvotes: 14
Reputation: 41
This answer is specifically for Lua 5.1.X
you can use
if( (bit.band(command,0x80)) == 0) then
...
in Lua 5.3.X and onwards it's very straight forward...
print(5 & 6)
hope that helped 😉
Upvotes: 3
Reputation: 11
Here's an example of how i bitwise-and a value with a constant 0x8000
:
result = (value % 65536) - (value % 32768) -- bitwise and 0x8000
Upvotes: 1
Reputation: 109
In case you use Adobe Lightroom Lua, Lightroom SDK contains LrMath.bitAnd()
method for "bitwise AND" operation:
-- x = a AND b
local a = 11
local b = 6
local x = import 'LrMath'.bitAnd(a, b)
-- x is 2
And there are also LrMath.bitOr(a, b)
and LrMath.bitXor(a, b)
methods for "bitwise OR" and "biwise XOR" operations.
Upvotes: 0
Reputation: 6251
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)
Upvotes: 5