且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在Swift中将十六进制字符串转换为UInt8字节数组?

更新时间:2021-08-12 05:23:54

您可以将您的六进制字符串转换回UInt8数组,该数组每隔六个六进制字符和ini进行迭代使用UInt8基数16初始化程序从其中初始化UInt8:

You can convert your hexa string back to array of UInt8 iterating every two hexa characters and initialize an UInt8 from it using UInt8 radix 16 initializer:

编辑/更新: Xcode 14•Swift 5.1

extension StringProtocol {
    var hexaData: Data { .init(hexa) }
    var hexaBytes: [UInt8] { .init(hexa) }
    private var hexa: UnfoldSequence<UInt8, Index> {
        sequence(state: startIndex) { start in
            guard start < self.endIndex else { return nil }
            let end = self.index(start, offsetBy: 2, limitedBy: self.endIndex) ?? self.endIndex
            defer { start = end }
            return UInt8(self[start..<end], radix: 16)
        }
    }
}







let string = "e0696349774606f1b5602ffa6c2d953f"
let data = string.hexaData.   // 16 bytes
let bytes = string.hexaBytes  // [224, 105, 99, 73, 119, 70, 6, 241, 181, 96, 47, 250, 108, 45, 149, 63]






快速3

extension StringProtocol {
    var hexa: [UInt8] {
        var startIndex = self.startIndex
        return stride(from: 0, to: count, by: 2).compactMap { _ in
            let endIndex = index(startIndex, offsetBy: 2, limitedBy: self.endIndex) ?? self.endIndex
            defer { startIndex = endIndex }
            return UInt8(self[startIndex..<endIndex], radix: 16)
        }
    }
}






游乐场:

let hexaString = "e0696349774606f1b5602ffa6c2d953f"

let bytes = hexaString.hexa   // [224, 105, 99, 73, 119, 70, 6, 241, 181, 96, 47, 250, 108, 45, 149, 63]