hex/binary string conversion in Swift

后端 未结 3 1557
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-11-27 23:38

Python has two very useful library method (binascii.a2b_hex(keyStr) and binascii.hexlify(keyBytes)) which I have been struggling with in Swift. Is there anything readily ava

3条回答
  •  情深已故
    2020-11-28 00:31

    Swift 2

    extension NSData {
        class func dataFromHexString(hex: String) -> NSData? {
            let regex = try! NSRegularExpression(pattern: "^[0-9a-zA-Z]*$", options: .CaseInsensitive)
            let validate = regex.firstMatchInString(hex, options: NSMatchingOptions.init(rawValue: 0), range: NSRange(location: 0, length: hex.characters.count))
            if validate == nil || hex.characters.count % 2 != 0 {
                return nil
            }
            let data = NSMutableData()
            for i in 0..

提交回复
热议问题