lua-users home
lua-l archive

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


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