Code: Select all
-- Converts a byte to a string of 0s and 1s.
function byte2bin(n)
local t = {}
for i=7,0,-1 do
t[#t+1] = math.floor(n / 2^i)
n = n % 2^i
end
return table.concat(t)
end
Code: Select all
-- Converts a byte to a string of 0s and 1s.
function byte2bin(n)
local t, d = {}, 0
d = math.log(n)/math.log(2) -- binary logarithm
for i=math.floor(d+1),0,-1 do
t[#t+1] = math.floor(n / 2^i)
n = n % 2^i
end
return table.concat(t)
end
Code: Select all
-- Converts a byte to a string of 0s and 1s.
function byte2bin(n)
local t, d = {}, 0
d = math.log(n)/math.log(2) -- binary logarithm
if n<0 then
-- two's complement
d = d + 1
n = 2^d - math.abs(n)
end
for i=math.floor(d+1),0,-1 do
n = n % 2^i
end
return table.concat(t)
end