Page 3 of 3

Re: Decimal to Binary function I made

Posted: Tue Jul 21, 2015 6:15 pm
by airstruck
slime wrote:LuaJIT doesn't specifically compile individual functions
Got it, I'll stay away from that until I figure out LuaJIT's profiler well enough to get a good idea of what's being compiled and what's not.

Just for fun, here's an FFI solution that's about 50% faster than the table lookup solution (and handles arbitrary bases).

Code: Select all

local function toBase (base, number)
    local bufferLength = 256
    local buffer = ffi.new('char[?]', bufferLength)
    local index = bufferLength - 1
    while number > 0 do
        if index <= 0 then error 'oops' end
        local digit = number % base
        index = index - 1
        buffer[index] = digit < 10 and 48 + digit or 55 + digit
        number = math.floor(number / base)
    end
    return ffi.string(buffer + index)
end
Magic numbers FTW.