Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"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

like image 945
Fusseldieb Avatar asked Sep 03 '15 23:09

Fusseldieb


People also ask

Does Lua have Bitwise Operators?

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.

What does a Bitwise and do?

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.

What is expression in Lua?

< Lua Programming. As explained before, expressions are pieces of code that have a value and that can be evaluated.

What are the bitwise operators in Lua programming?

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.

What is ‘and’ operator in Lua?

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.

What does result mean in Lua?

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?

What is wrong with the rshift function 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.


1 Answers

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
like image 121
Egor Skriptunoff Avatar answered Sep 18 '22 00:09

Egor Skriptunoff