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
As of version 5.2, Lua ships with the library [bit32] that adds support for bitwise operations. Previous versions of Lua did not include bitwise operators, but bit32 has been backported to version 5.1. Alternatively, there are Lua libraries for this as well as some patched versions of Lua.
Remarks. The bitwise AND operator ( & ) compares each bit of the first operand to the corresponding bit of the second operand. If both bits are 1, the corresponding result bit is set to 1. Otherwise, the corresponding result bit is set to 0.
< Lua Programming. As explained before, expressions are pieces of code that have a value and that can be evaluated.
3.4.2 – Bitwise Operators. Lua supports the following bitwise operators: &: bitwise AND |: bitwise OR ~: bitwise exclusive OR >>: right shift <<: left shift ~: unary bitwise NOT; All bitwise operations convert its operands to integers (see §3.4.3), operate on all bits of those integers, and result in an integer.
Lua ‘and’ operator is a logical operator that is used widely in the programs by providing the 2 operands and applying the operator between them. In Lua, ‘and’ operator works a little bit different in comparison to the other programming languages.
In Lua ‘result’ variable will hold either the value of ‘operand1’ or ‘operand2’ instead of the boolean true or false values depending on the value that variable holds. How does an ‘and’ operator work in Lua?
Functions for quick left and right bitwise shifts in Lua. There seems to be a bug in the rshift function as defined here. Shifting a value of 0x01 twice should result in a value of 0 while shifting a value of 0x03 twice should result in a value of 1. Lua will return 0 for both of these operations as shown below.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With