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? 

Not a built-in function, mainly because sprintf does not do that.
Try this Lua code:

 function binary(x)
  local s=format("%o",x)
  local a={["0"]="000",["1"]="001", ["2"]="010",["3"]="011",
           ["4"]="100",["5"]="101", ["6"]="110",["7"]="111"}
  s=gsub(s,"(.)",function (d) return %a[d] end)
  return s

 for i=0,20 do

If you want a fixed number of digits, add it to %o.