Converting Hex String to NSData in Swift

后端 未结 11 1215
一生所求
一生所求 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:49

    Here is my Swifty 5 way to do it:

    • does take care of "0x" prefixes
    • use subscript instead of allocated Array(), no C style [i+1] too
    • add .hexadecimal to String.data(using encoding:) -> Data?

    .

    String Extension:

        extension String {
            enum ExtendedEncoding {
                case hexadecimal
            }
    
            func data(using encoding:ExtendedEncoding) -> Data? {
                let hexStr = self.dropFirst(self.hasPrefix("0x") ? 2 : 0)
    
                guard hexStr.count % 2 == 0 else { return nil }
    
                var newData = Data(capacity: hexStr.count/2)
    
                var indexIsEven = true
                for i in hexStr.indices {
                    if indexIsEven {
                        let byteRange = i...hexStr.index(after: i)
                        guard let byte = UInt8(hexStr[byteRange], radix: 16) else { return nil }
                        newData.append(byte)
                    }
                    indexIsEven.toggle()
                }
                return newData
            }
        }
    

    Usage:

        "5413".data(using: .hexadecimal)
        "0x1234FF".data(using: .hexadecimal)
    

    Tests:

        extension Data {
            var bytes:[UInt8] { // fancy pretty call: myData.bytes -> [UInt8]
                return [UInt8](self)
            }
    
            // Could make a more optimized one~
            func hexa(prefixed isPrefixed:Bool = true) -> String {
                return self.bytes.reduce(isPrefixed ? "0x" : "") { $0 + String(format: "%02X", $1) }
            }
        }
    
        print("000204ff5400".data(using: .hexadecimal)?.hexa() ?? "failed") // OK
        print("0x000204ff5400".data(using: .hexadecimal)?.hexa() ?? "failed") // OK
        print("541".data(using: .hexadecimal)?.hexa() ?? "failed") // fails
        print("5413".data(using: .hexadecimal)?.hexa() ?? "failed") // OK
    

提交回复
热议问题