BaseConverter - Convert number from Base2 to Base36

Title explains it all. Its just a module that converts given number to BaseN (2 <= N <= 36)

it has 3 functions:

  • Base10_to_BaseK : (Base10Number: number, k: number) -> (string) - Converts Base10 to BaseN
  • BaseK_to_Base10: (BaseKNumber: number, k: number) -> (number) - Converts BaseK to Base10
  • BaseK_to_BaseN: (BaseKNumber: number, k: number, n: number) -> (number) - Converts BaseK to BaseN

  • Code:
local BaseConverter = {}

local Symbols = "0123456789abcdefghijklmnopqrstuvwxyz"

function BaseConverter.Base10_to_BaseK(Base10Number: number,k: number)
    local BaseK = ""

    while Base10Number > 0 do
        local n = math.fmod(Base10Number,k) + 1

        BaseK = Symbols:sub(n,n)..BaseK
        Base10Number = math.floor(Base10Number / k)
    end

    return BaseK
end

BaseConverter.BaseK_to_Base10 = tonumber :: (BaseKNumber: string,k: number) -> (number)

function BaseConverter.BaseK_to_BaseN(BaseKNumber: string,k: number,n: number)
    local Base10 = BaseConverter.BaseKToBase10(BaseKNumber,k)
    
    return BaseConverter.Base10ToBaseK(Base10,n)
end

return BaseConverter

That’s all. Feel free to use :)

2 Likes