How can I implement bitwise operators in Lua language?
Specifically, I need a XOR operator/method.
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.
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.
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 .
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.
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
In Lua 5.2, you can use the bit32.bxor
function.
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