-
-
Save kindy/2909817 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' | |
} |
python based int2base
import string
digs = string.digits + string.lowercase
def int2base(x, base):
if x < 0: sign = -1
elif x==0: return '0'
else: sign = 1
x *= sign
digits = []
while x:
digits.append(digs[x % base])
x /= base
if sign < 0:
digits.append('-')
digits.reverse()
return ''.join(digits)
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
the talk is on http://lua-list.2524044.n2.nabble.com/tostring-e-base-td6621781.html
another impl.