function toBinary(int)
if(type(int)=="number")then
local current = int
local bin = {}
while(current~=0)do
table.insert(bin, current%2)
current = math.floor(current / 2)
end
local result = ""
for i,v in pairs(bin) do
result = result .. v
end
return string.reverse(result)
end
return "error: string input"
end
function toBinary( int )
assert( type( int ) == 'number', 'Error: Non-number input to toBinary!' )
local current = math.floor( int )
local result = ''
while( current ~= 0 ) do
result = result..current % 2
current = math.floor( current / 2)
end
return ( '%08s' ):format( string.reverse( result ) )
end
function toBinary( int )
assert( type( int ) == 'number', 'Error: Non-number input to toBinary!' )
local current = math.floor( int )
local result = ''
while( current ~= 0 ) do
result = result..current % 2
current = math.floor( current / 2)
end
return ( '%08s' ):format( string.reverse( result ) )
end
That's true, thank you. Not much of a code golfer myself
local function toBase (base, number)
local result = {}
while number > 0 do
local digit = number % base
result[#result + 1] = digit < 10 and digit or string.char(55 + digit)
number = math.floor(number / base)
end
return string.reverse(table.concat(result))
end
do
local conv = {}
for i = 0, 7 do
conv[tostring(i)] = ("%d%d%d"):format(math.floor(i%8/4), math.floor(i%4/2), math.floor(i%2/1))
end
function tobinary(n)
return (("%o"):format(n):gsub(".", conv):match("1.+$"))
end
end
print(tobinary(4713))
It still doesn't strike me as efficient, though.
EDIT: I just realized the match doesn't quite work for 0, oops. (Just add 'or 0'.)