Skip to content

Instantly share code, notes, and snippets.

@stuartpb
Created February 2, 2011 02:45
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save stuartpb/807158 to your computer and use it in GitHub Desktop.
Save stuartpb/807158 to your computer and use it in GitHub Desktop.
Function for using arbitrary digit systems to convert numbers to strings
local function base (digit_list)
local b = #digit_list
if b == 0 then
return function(number) return "" end
elseif b == 1 then
local mark = digit_list[1]
return function(number)
return string.rep(mark, number)
end
else
return function(number)
number=math.floor(number)
if number == 0 then
return digit_list[1]
end
local places={}
local pow=0
local digits=math.floor(math.log(number) / math.log(b))+1
for pow=digits,1,-1 do
places[#places+1] = digit_list[
(number % b^pow
-number % b^(pow-1))
/b^(pow-1) + 1]
end
return table.concat(places)
end
end
end
local bbar = base{"|"}
local b2 = base{'0','1'}
local b10 = base{
'0','1','2','3','4','5','6','7','8','9',
}
local bten = base{
'zero','one','two','three','four','five','six','seven','eight','nine',
}
local b32 = base{
'0','1','2','3','4','5','6','7','8','9',
'A','B','C','D','E','F','G','H','J','K',
'L','M','N','P','Q','R','S','T','U','V',
'W','X'
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment