How to convert Data to hex string in swift

前端 未结 7 1949
走了就别回头了
走了就别回头了 2020-11-22 07:59

I want the hexadecimal representation of a Data value in Swift.

Eventually I\'d want to use it like this:

let data = Data(base64Encoded: \"aGVsbG8gd2         


        
7条回答
  •  无人及你
    2020-11-22 08:04

    A bit different from other answers here:

    extension DataProtocol {
        func hexEncodedString(uppercase: Bool = false) -> String {
            return self.map {
                if $0 < 16 {
                    return "0" + String($0, radix: 16, uppercase: uppercase)
                } else {
                    return String($0, radix: 16, uppercase: uppercase)
                }
            }.joined()
        }
    }
    

    However in my basic XCTest + measure setup this was fastest of the 4 I tried.

    Going through a 1000 bytes of (the same) random data 100 times each:

    Above: Time average: 0.028 seconds, relative standard deviation: 1.3%

    MartinR: Time average: 0.037 seconds, relative standard deviation: 6.2%

    Zyphrax: Time average: 0.032 seconds, relative standard deviation: 2.9%

    NickMoore: Time average: 0.039 seconds, relative standard deviation: 2.0%

    Repeating the test returned the same relative results. (Nick and Martins sometimes swapped)

提交回复
热议问题