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]
*/