Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I use the bitwise operator XOR in Lua?

How can I implement bitwise operators in Lua language?
Specifically, I need a XOR operator/method.

like image 378
Trevor Avatar asked May 12 '11 12:05

Trevor


People also ask

How do you perform bitwise XOR operations?

The ^ (bitwise XOR) in C or C++ takes two numbers as operands and does XOR on every bit of two numbers. The result of XOR is 1 if the two bits are different. The << (left shift) in C or C++ takes two numbers, left shifts the bits of the first operand, the second operand decides the number of places to shift.

Does Lua have Bitwise Operators?

Implementations of bitwise operators in Lua: C Library implementations: [Lua BitOp] (5.1) - C library providing bitwise operations on fixed-sized bitfields implemented as Lua numbers. Has consistent semantics across 16, 32 and 64 bit platforms as well as IEEE 754 doubles, int32_t and int64_t lua_Number types.

How does Bitwise operator XOR works explain with example?

Each bit in the first operand is paired with the corresponding bit in the second operand: first bit to first bit, second bit to second bit, and so on. The operator is applied to each pair of bits, and the result is constructed bitwise. Bitwise XORing any number x with 0 yields x .

What is the symbol for bitwise XOR?

The bitwise XOR operator is written using the caret symbol ^ . A bitwise XOR operation results in a 1 only if the input bits are different, else it results in a 0.


2 Answers

In Lua 5.2, you can use functions in bit32 library.

In Lua 5.3, bit32 library is obsoleted because there are now native bitwise operators.

print(3 & 5)  -- bitwise and
print(3 | 5)  -- bitwise or
print(3 ~ 5)  -- bitwise xor
print(7 >> 1) -- bitwise right shift
print(7 << 1) -- bitwise left shift
print(~7)     -- bitwise not

Output:

1
7
6
3
14
-8
like image 107
Yu Hao Avatar answered Sep 22 '22 03:09

Yu Hao


In Lua 5.2, you can use the bit32.bxor function.

like image 24
Stuart P. Bentley Avatar answered Sep 21 '22 03:09

Stuart P. Bentley