Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,885 questions

51,811 answers

573 users

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, 2025 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, 2025 by avibootz

Related questions

1 answer 56 views
2 answers 76 views
1 answer 102 views
1 answer 78 views
1 answer 103 views
...