How do I use the bitwise operator XOR in Lua?

Trevor  picture Trevor · May 12, 2011 · Viewed 42.5k times · Source

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

Answer

Yu Hao picture Yu Hao · Jan 16, 2015

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