How to convert Data to hex string in swift

前端 未结 7 2252
走了就别回头了
走了就别回头了 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:06

    My version. It's about 10 times faster than the [original] accepted answer by Martin R.

    public extension Data {
        private static let hexAlphabet = Array("0123456789abcdef".unicodeScalars)
        func hexStringEncoded() -> String {
            String(reduce(into: "".unicodeScalars) { result, value in
                result.append(Self.hexAlphabet[Int(value / 0x10)])
                result.append(Self.hexAlphabet[Int(value % 0x10)])
            })
        }
    }
    

提交回复
热议问题