Skip to content

Instantly share code, notes, and snippets.

@kindy
Forked from stuartpb/arbase.lua
Created June 11, 2012 12:17
Show Gist options
  • Save kindy/2909817 to your computer and use it in GitHub Desktop.
Save kindy/2909817 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'
}
@kindy
Copy link
Author

kindy commented Jun 11, 2012

the talk is on http://lua-list.2524044.n2.nabble.com/tostring-e-base-td6621781.html

another impl.

local math = require( 'math' ) 
local table = require( 'table' ) 
local assert = assert 
local tonumber = tonumber 
local abs, floor = math.abs, math.floor 

local base = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z' } 

local function tobase( aNumber, aBase ) 
    assert( aNumber, 'bad argument #1 to \'tobase\' (nil number)' ) 
    assert( aBase and aBase >= 2 and aBase <= #base, 'bad argument #2 to \'tobase\' (base out of range)' ) 

    local isNegative = aNumber < 0 
    local aNumber = abs( floor( tonumber( aNumber ) ) ) 
    local aBuffer = {} 

    repeat 
        aBuffer[ #aBuffer + 1 ] = base[ ( aNumber % aBase ) + 1 ] 
        aNumber = floor( aNumber / aBase ) 
    until aNumber == 0 

    if isNegative then 
        aBuffer[ #aBuffer + 1 ] = '-' 
    end 

    return table.concat( aBuffer ):reverse() 
end 

@kindy
Copy link
Author

kindy commented Mar 12, 2014

python based int2base

http://stackoverflow.com/questions/2267362/convert-integer-to-a-string-in-a-given-numeric-base-in-python

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