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

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

Leave a Comment

tech