swiftswift3byte

How do i convert HexString To ByteArray in Swift 3


I'm was trying to convert hexString to Array of Bytes([UInt8]) I searched everywhere but couldn't find a solution. Below is my swift 2 code

func stringToBytes(_ string: String) -> [UInt8]? {
    let chars = Array(string)
    let length = chars.count
    if length & 1 != 0 {
        return nil
    }
    var bytes = [UInt8]()
    bytes.reserveCapacity(length/2)
    for var i = 0; i < length; i += 2 {
        if let a = find(hexChars, chars[i]),
            let b = find(hexChars, chars[i+1]) {
            bytes.append(UInt8(a << 4) + UInt8(b))
        } else {
            return nil
        }
    }
    return bytes
} 

Example Hex

Hex : "7661706f72"

expectedOutput : "vapor"


Solution

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

    func stringToBytes(_ string: String) -> [UInt8]? {
        // let length = string.characters.count
        // Updating / replacing previous (now commented) line for Swift 5 (2023-12)
        // No longer need reference characters.
        let length = string.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")