Skip to content

Instantly share code, notes, and snippets.

@irgendwr
Created August 16, 2021 15:27
Show Gist options
  • Save irgendwr/98618fa602874503015d98cbc1471edf to your computer and use it in GitHub Desktop.
Save irgendwr/98618fa602874503015d98cbc1471edf to your computer and use it in GitHub Desktop.
Bitwise Operator implementations in native Lua.
-- Bitwise Operator implementations in native Lua.
-- Play around with it here: https://replit.com/@irgendwr/lua-bitwise-operators
-- Lua only has native support for bitwise operators since 5.3+
-- see https://www.lua.org/manual/5.3/manual.html#3.4.2
-- and http://lua-users.org/wiki/BitwiseOperators
--[[
SHIFTING
Shifting right is essentially just dividing by 2.
Shifting left is essentially just multiplying by 2.
Note that Lua converts numbers to floats when dividing,
so you need to apply math.floor() to get an integer.
--]]
--[[
BIT MASKS
Reading the rightmost ("first") bit can be done by calculating modulo 2 and comparing against 1.
Odd numbers have the last bit set, while even numbers do not.
There is a crazy hack for bitwise OR, XOR, AND: https://stackoverflow.com/a/32389020/4884643
Unfortunately the function is not very readable.
--]]
-- This is a hack for checking if a certain bit is set.
-- pos starts counting at 0; the rightmost bit is the "first" one at pos=0.
function checkBit(value, pos)
-- shift right by pos
while pos > 0 and value ~= 0 do
value = math.floor(value / 2)
pos = pos - 1
end
-- get rightmost ("first") bit
return value % 2 == 1
end
-- Test prints
value = 7 -- Binary representation: 0111
print("Bits of the number 7 (binary representation: 0111). See code for details.")
print(checkBit(value, 0)) -- => true (1)
print(checkBit(value, 1)) -- => true (1)
print(checkBit(value, 2)) -- => true (1)
print(checkBit(value, 3)) -- => false (0)
@irgendwr
Copy link
Author

Play around with it here: https://replit.com/@irgendwr/lua-bitwise-operators

Lua only has native support for bitwise operators since 5.3+
see https://www.lua.org/manual/5.3/manual.html#3.4.2
and http://lua-users.org/wiki/BitwiseOperators.

Implementation of bitwise operations in Lua 5.1 for non-negative 32-bit integers: https://stackoverflow.com/a/32389020/4884643 (Unfortunately the function is not very readable)

Bitwise-and implementation in pure Lua 5.1: https://stackoverflow.com/a/32387452/4884643 (this one is very readable)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment