How about using the basic base 10 to any base conversion, modified for custom digits:
func numberToCustomRadix(_ number: Int, alphabet: String) -> String {
let base = alphabet.count
var number = number
var result = ""
repeat {
let idx = alphabet.index(alphabet.startIndex, offsetBy: number % base)
result = [alphabet[idx]] + result
number /= base
} while number > 0
return result
}
numberToCustomRadix(3, alphabet: "012") // 10
numberToCustomRadix(4, alphabet: "abc") // bb
numberToCustomRadix(5, alphabet: "%#9") // #9
Note that the problem with a custom alphabet is the fact that it’s hard to guarantee at compile time that the alphabet contains distinct characters. E.g. an “aaabbbccc” alphabet will generate all kind of conversion problems.
7
solved Custom radix columns (+special characters) [closed]