自定义基数列(+特殊字符) [英] Custom radix columns (+special characters)

查看:76
本文介绍了自定义基数列(+特殊字符)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

目前我正在使用此代码将数字转换为 base36 字符串:

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

但我想知道如何使用 Swift 通过一种 Base10 到 AnyBase 的转换来生成我自己的字母表.

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", "=", "?", "+", "#", "-", ".", ">", "<", "*", "!", ...]

它可能看起来像这样:

let number = 300293338
let base36 = mycoolfunction(number)
print(base36) // "$%//+#="

推荐答案

如何使用基本的基数 10 到任何基数转换,修改自定义数字:

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

请注意,自定义字母表的问题在于,在编译时很难保证字母表包含不同的字符.例如.aaabbbccc"字母表会产生各种转换问题.

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.

这篇关于自定义基数列(+特殊字符)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆