Jump to content

Module:BaseConvert

Permanently protected module
From Wikipedia, the free encyclopedia
This is an old revision of this page, as edited by Toohool (talk | contribs) at 09:38, 22 February 2013 (Created page with '-- -- Converts numbers to a specified base between 2 and 36, for use in -- templates such as {{binary}}, {{octal}}, {{hexadecimal}}, etc. -- local p = {} funct...'). The present address (URL) is a permanent link to this revision, which may differ significantly from the current revision.
(diff) ← Previous revision | Latest revision (diff) | Newer revision → (diff)

--
-- Converts numbers to a specified base between 2 and 36, for use in
-- templates such as {{binary}}, {{octal}}, {{hexadecimal}}, etc.
--

local p = {}

function p._convert(n, base)
    local digits = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ'

    n = math.floor(n)
    local sign = ''
    if n < 0 then
        sign = '-'
        n = -n
    end
    
    local t = {}
    repeat
        local d = (n % base) + 1
        n = math.floor(n / base)
        table.insert(t, 1, digits:sub(d, d))
    until n == 0
    
    return sign .. table.concat(t, '')
end

function p.convert(frame)
    local n = frame.args.n
    local base = frame.args.base
    return p._convert(n, base)
end

return p