How do convert base 10 to base N given set of extra characters to work with?

How would I convert a base 10 number to a base N number given a set of N-10 characters to work with (always using 012345679 and the set represents numbers after)?

Example 1

Number (base 10): 25
New Base: 13
Character Set: ABC (A = 10, B = 11, C = 11)

How could I transcribe 25 from base 10 to base 13?

The answer for this case would be: 1C (13 + 12)

Example 2

Number (base 10): 4238
New Base: 14
Character Set: ABC (A = 10, B = 11, C = 11, D = 12)

How could I transcribe 4238 from base 10 to base 14?

The answer for this case would be: 178A (2744 + 1372 + 112 + 10)

What I’ve Tried

I tried loop division for long as the remainder of a loop is greater than 1, however I’m not sure where to go from there.

local Input = 25
local NewBase = 13

local CharacterSet = "0123456789ABC"

while Input > 1 do
    local Quotient = math.floor(Input / NewBase)
    local Remainder = Input % NewBase

    local Character = CharacterSet:sub(Remainder + 1, Remainder + 1)

    Input = Quotient
end
1 Like

I got it, I just made a silly mistake in my logic.

I fiddled with my code a bit more and realized I have basically done all I needed to do. I was attempting to append my characters from least significant to most significant, and so I was confused initially when looking at my code. I also should be doing Input > 0 rather than Input > 1

local Input = 4238
local NewBase = 14

local CharacterSet = "0123456789ABCD"
local String = ""

while Input > 0 do
    local Quotient = math.floor(Input / NewBase)
    local Remainder = Input % NewBase

    local Character = CharacterSet:sub(Remainder + 1, Remainder + 1)

	String = String .. Character
    Input = Quotient
end

print(String:reverse())
2 Likes