问题
Currently I'm using this code to convert a number into an base36-string:
let number = 300293338
let base36 = String(number, radix: 36);
print(base36) // 4ysbtm
But I'm wondering how it's possible to generate my own alphabet with a kind of a Base10 to AnyBase conversion using Swift.
An example of the alphabet could be something like this:
["$", "%", "&", "/", "(", "9", "=", "?", "+", "#", "-", ".", ">", "<", "*", "!", ...]
It maybe could look like this:
let number = 300293338
let base36 = mycoolfunction(number)
print(base36) // "$%//+#="
回答1:
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.
来源:https://stackoverflow.com/questions/48724055/custom-radix-columns-special-characters