Created
February 2, 2011 02:45
-
-
Save stuartpb/807158 to your computer and use it in GitHub Desktop.
Function for using arbitrary digit systems to convert numbers to strings
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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