How do i convert HexString To ByteArray in Swift 3

This code can generate the same output as your swift 2 code.

func stringToBytes(_ string: String) -> [UInt8]? {
    let length = string.characters.count
    if length & 1 != 0 {
        return nil
    }
    var bytes = [UInt8]()
    bytes.reserveCapacity(length/2)
    var index = string.startIndex
    for _ in 0..<length/2 {
        let nextIndex = string.index(index, offsetBy: 2)
        if let b = UInt8(string[index..<nextIndex], radix: 16) {
            bytes.append(b)
        } else {
            return nil
        }
        index = nextIndex
    }
    return bytes
}

let bytes = stringToBytes("7661706f72")
print(String(bytes: bytes!, encoding: .utf8)) //->Optional("vapor")

Following code may be help for you

extension String {

/// Create `Data` from hexadecimal string representation
///
/// This takes a hexadecimal representation and creates a `Data` object. Note, if the string has any spaces or non-hex characters (e.g. starts with '<' and with a '>'), those are ignored and only hex characters are processed.
///
/// - returns: Data represented by this hexadecimal string.

func hexadecimal() -> Data? {
    var data = Data(capacity: characters.count / 2)

    let regex = try! NSRegularExpression(pattern: "[0-9a-f]{1,2}", options: .caseInsensitive)
    regex.enumerateMatches(in: self, options: [], range: NSMakeRange(0, characters.count)) { match, flags, stop in
        let byteString = (self as NSString).substring(with: match!.range)
        var num = UInt8(byteString, radix: 16)!
        data.append(&num, count: 1)
    }

    guard data.count > 0 else {
        return nil
    }

    return data
 }
}

extension String {

/// Create `String` representation of `Data` created from hexadecimal string representation
///
/// This takes a hexadecimal representation and creates a String object from that. Note, if the string has any spaces, those are removed. Also if the string started with a `<` or ended with a `>`, those are removed, too.

init?(hexadecimal string: String) {
    guard let data = string.hexadecimal() else {
        return nil
    }

    self.init(data: data, encoding: .utf8)
}

/// - parameter encoding: The `NSStringCoding` that indicates how the string should be converted to `NSData` before performing the hexadecimal conversion.

/// - returns: `String` representation of this String object.

func hexadecimalString() -> String? {
    return data(using: .utf8)?
        .hexadecimal()
}

 }

  extension Data {

/// Create hexadecimal string representation of `Data` object.

/// - returns: `String` representation of this `Data` object.

func hexadecimal() -> String {
    return map { String(format: "%02x", $0) }
        .joined(separator: "")
}
}

Use like this :

let hexString = "68656c6c 6f2c2077 6f726c64"
print(String(hexadecimalString: hexString))

Or

let originalString = "hello, world"
print(originalString.hexadecimalString())

Here is a sketch of how I'd do it in a more idiomatic Swift style (this might be Swift 4 only):

func toPairsOfChars(pairs: [String], string: String) -> [String] { 
    if string.count == 0 {
        return pairs
    } 
    var pairsMod = pairs
    pairsMod.append(String(string.prefix(2))) 
    return toPairsOfChars(pairs: pairsMod, string: String(string.dropFirst(2))) 
}

func stringToBytes(_ string: String) -> [UInt8]? {
    // omit error checking: remove '0x', make sure even, valid chars
    let pairs = toPairsOfChars(pairs: [], string: string)
    return pairs.map { UInt8($0, radix: 16)! }
}

Tags:

Byte

Swift

Swift3