How to convert hexadecimal string to an array of UInt8 bytes in Swift?

后端 未结 3 691
灰色年华
灰色年华 2020-12-03 17:37

I have the following code:

var encryptedByteArray: Array?
do {
    let aes = try AES(key: \"passwordpassword\", iv: \"drowssapdrowssap\")
    e         


        
3条回答
  •  半阙折子戏
    2020-12-03 18:03

    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:


    Edit/update: Xcode 14 • Swift 5.1

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

    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]
    

    Playground:

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

提交回复
热议问题