lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]


Actually, you can accept bases lower than 2: you just have to treat them as special cases.

I wrote a similar function a while back (oriented toward arbitrary digit systems, such as a base 32 that doesn't use I or O), except that it doesn't use reverse() after concatenating, so you can use digits of any length:
https://gist.github.com/807158

On Tue, 26 Jul 2011 11:29:42 -0400, Petite Abeille <petite.abeille@gmail.com> wrote:


On Jul 26, 2011, at 1:27 PM, Duncan Cross wrote:

For symmetry, `tostring (e [, base])` would be nice to have:

FWIW, here is a little tobase function:

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


Usage example:

print( tobase( 6700417, 36 ), tonumber( tobase( 6700417, 36 ), 36 ) )

3ZM2P	6700417