lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]


> I would like to convert a number, say 4, to binary so that it would
> read "00000100". Is there a simple LUA function that would do that?
> Thanks in advance for any insights.

the other way round would be easy: tonumber() allows you to specify the
base, so

> print(tonumber("0100",2))
4

i'm afraid there is no standard function for the other way round. but it is
easy to make one yourself:

digits = {}
for i=0,9 do digits[i] = strchar(strbyte('0')+i) end
for i=10,36 do digits[i] = strchar(strbyte('A')+i-10) end

function numberstring(number, base)
   local s = ""
   repeat
      local remainder = mod(number,base)
      s = digits[remainder]..s
      number = (number-remainder)/base
   until number==0
   return s
end

> print(numberstring(4,2))
100

Cheers,
Peter