Left Shift
Example:
Right Shift
Example:
Number To Binary
Example:
Binary to Number
Example:
Bitwise Operations
Example:
Code:
function lshift(x, y)
return x * 2 ^ y
end
Code:
print( lshift(1, 11) ) -- prints 2048
Right Shift
Code:
function rshift(x, y)
return math.floor(x / 2 ^ y)
end
Code:
print( rshift(11, 1) ) -- prints 5
Number To Binary
Code:
function getBits(num, asString)
local x = {}
while num > 0 do
rest = num % 2
table.insert(x, 1, rest)
num = (num - rest) / 2
end
return asString and table.concat(x) or x
end
Code:
print( getBits(67, true) ) -- prints 1000011
Binary to Number
Code:
function binToNum(binary)
local bin, sum = tostring(binary):reverse(), 0
for i = 1, #bin do
num = bin:sub(i, i) == "1" and 1 or 0
sum = sum + num * math.pow(2, i - 1)
end
return sum
end
Code:
print( binToNum(1000011) ) -- prints 67
Bitwise Operations
Code:
function bitwise(bits, c, oper)
local t = {}
for k, v in pairs(bits) do
if oper == "and" then
if (v == 1 and c[k] == 1) then
table.insert(t, 1)
else
table.insert(t, 0)
end
elseif oper == "or" then
if (v == 1 or c[k] == 1) then
table.insert(t, 1)
else
table.insert(t, 0)
end
elseif oper == "xor" then
if ((v == 1 and c[k] ~= 1) or ( c[k] == 1 and v ~= 1) ) then
table.insert(t, 1)
else
table.insert(t, 0)
end
elseif oper == "not" then
table.insert(t, (v == 0 and 1 or 0))
else
-- just a default for testing
table.insert(t, v)
end
end
return table.concat(t)
end
Code:
local binary = bitwise(getBits(48), getBits(5), "xor")
print(binary, binToNum(binary))
-- prints 011000 24