Decimal to Binary function I made

General discussion about LÖVE, Lua, game development, puns, and unicorns.
User avatar
airstruck
Party member
Posts: 650
Joined: Thu Jun 04, 2015 7:11 pm
Location: Not being time thief.

Re: Decimal to Binary function I made

Post 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.
Post Reply

Who is online

Users browsing this forum: Bing [Bot] and 1 guest