Converting Hex String to NSData in Swift

后端 未结 11 1286
一生所求
一生所求 2020-11-27 05:22

I got the code to convert String to HEX-String in objective-C.

- (NSString *) CreateDataWithHexString:(NSString*)inputString
{
NSUInteger inLength = [inputSt         


        
11条回答
  •  时光说笑
    2020-11-27 06:03

    Here is my take on converting hexadecimal string to Data using Swift 4:

    extension Data {
        private static let hexRegex = try! NSRegularExpression(pattern: "^([a-fA-F0-9][a-fA-F0-9])*$", options: [])
    
        init?(hexString: String) {
            if Data.hexRegex.matches(in: hexString, range: NSMakeRange(0, hexString.count)).isEmpty {
                return nil // does not look like a hexadecimal string
            }
    
            let chars = Array(hexString)
    
            let bytes: [UInt8] = 
                stride(from: 0, to: chars.count, by: 2)
                    .map {UInt8(String([chars[$0], chars[$0+1]]), radix: 16)}
                    .compactMap{$0}
    
            self = Data(bytes)
        }
    
        var hexString: String {
            return map { String(format: "%02hhx", $0) }.joined()
        }
    }
    

    (I threw in a small feature for converting back to hex string I found in this answer)

    And here is how you would use it:

        let data = Data(hexString: "cafecafe")
    
        print(data?.hexString) // will print Optional("cafecafe")
    

提交回复
热议问题