Converting Hex String to NSData in Swift

后端 未结 11 1285
一生所求
一生所求 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 05:55

    Swift 5

    extension Data {
        init?(hex: String) {
            guard hex.count.isMultiple(of: 2) else {
                return nil
            }
            
            let chars = hex.map { $0 }
            let bytes = stride(from: 0, to: chars.count, by: 2)
                .map { String(chars[$0]) + String(chars[$0 + 1]) }
                .compactMap { UInt8($0, radix: 16) }
            
            guard hex.count / bytes.count == 2 else { return nil }
            self.init(bytes)
        }
    }
    

提交回复
热议问题