How to convert a hex to a byte array in Swift

2 Answers

0 votes
import Foundation

func hexStringToByteArray(_ hex: String) -> [UInt8]? {
    var hex = hex
    var byteArray = [UInt8]()
    let len = hex.count
    
    // Ensure the hex string has an even number of characters
    if len % 2 != 0 {
        hex = "0" + hex
    }
    
    // Convert hex string to byte array
    for i in stride(from: 0, to: len, by: 2) {
        let start = hex.index(hex.startIndex, offsetBy: i)
        let end = hex.index(start, offsetBy: 2)
        let byteString = hex[start..<end]
        if let byte = UInt8(byteString, radix: 16) {
            byteArray.append(byte)
        } else {
            return nil // Return nil if conversion fails
        }
    }
    
    return byteArray
}

if let byteArray = hexStringToByteArray("1A2D3E4F") {
    print(byteArray) 
} else {
    print("Invalid hex string")
}



/*
run:

[26, 45, 62, 79]

*/

 



answered Feb 15 by avibootz
0 votes
import Foundation

let hexString = "1A2D3E4F"

let bytes = stride(from: 0, to: hexString.count, by: 2).map { i -> UInt8 in
    let startIndex = hexString.index(hexString.startIndex, offsetBy: i)
    let endIndex = hexString.index(hexString.startIndex, offsetBy: i + 2)
    let byteString = hexString[startIndex..<endIndex]
    return UInt8(byteString, radix: 16)!
}

print(bytes)



/*
run:

[26, 45, 62, 79]

*/

 



answered Feb 15 by avibootz

Related questions

2 answers 41 views
1 answer 48 views
1 answer 43 views
1 answer 57 views
1 answer 46 views
46 views asked Nov 19, 2024 by avibootz
...