How to convert array of bytes [UInt8] into hexa string in Swift

Solution 1:

Xcode 11 • Swift 5.1 or later

extension StringProtocol {
    var hexa: [UInt8] {
        var startIndex = self.startIndex
        return (0..<count/2).compactMap { _ in
            let endIndex = index(after: startIndex)
            defer { startIndex = index(after: endIndex) }
            return UInt8(self[startIndex...endIndex], radix: 16)
        }
    }
}

extension DataProtocol {
    var data: Data { .init(self) }
    var hexa: String { map { .init(format: "%02x", $0) }.joined() }
}

"0f00ff".hexa                 // [15, 0, 255]
"0f00ff".hexa.data            // 3 bytes
"0f00ff".hexa.data.hexa       // "0f00ff"
"0f00ff".hexa.data as NSData  // <0f00ff>

Note: Swift 4 or 5 syntax click here

Solution 2:

Thanks to Brian for his routine. It could conveniently be added as a Swift extension as below.

 extension Array where Element == UInt8 {
  func bytesToHex(spacing: String) -> String {
    var hexString: String = ""
    var count = self.count
    for byte in self
    {
        hexString.append(String(format:"%02X", byte))
        count = count - 1
        if count > 0
        {
            hexString.append(spacing)
        }
    }
    return hexString
}

}

Example of call:

let testData: [UInt8] = [15, 0, 255]
print(testData.bytesToHex(spacing: " "))          // 0F 00 FF