当我自学 Swift 时,我正在尝试为应用程序实现 Base32 解码,但我似乎无法弄清楚如何在这种语言中低于字节级别。如果我可以将 UInt8 截断为 5 位并将其附加到我可以使用的 Data 对象中,那将会很方便。
我有这个用 Python 编写的函数:
def base32_decode(secret):
b32alphabet = list("ABCDEFGHIJKLMNOPQRSTUVWXYZ234567")
b32v = [b32alphabet.index(x) for x in secret if x != '=']
t1 = ["{0:0>5}".format(bin(v)[2:]) for v in b32v]
t2 = ''.join(t1)
t3 = textwrap.wrap(t2,8)
t4 = [int(v, 2) for v in t3 if len(v) == 8]
t5 = ''.join(["{0:0>2}".format(hex(v)[2:]) for v in t4])
它可以输出base32中数据的十六进制表示。我想在 Swift 中复制它(虽然不是转换为十六进制部分)。但是,我做到了这一点:
func base32decode(string: String) -> Data
{
let b32a: Array = ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z", "2", "3", "4", "5", "6", "7"]
let complete: NSMutableData = NSMutableData()
var b32v: Array<UInt8> = []
for c in string.characters
{
let index = b32a.index(of: String(c))!
b32v.append(UInt8(index)) // Need to append only the 5 LSB
}
// Return b32v as base 32 decoded data
...
是否有捷径可寻?我无法通过谷歌找到任何东西。