[Date Prev][Date Next][Thread Prev][Thread Next]
[Date Index]
[Thread Index]
- Subject: Re: Easy convert number to binary?
- From: Luiz Henrique de Figueiredo <lhf@...>
- Date: Mon, 28 Oct 2002 18:43:30 -0300
>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
end
for i=0,20 do
print(i,binary(i))
end
If you want a fixed number of digits, add it to %o.
--lhf