I want the hexadecimal representation of a Data value in Swift.
Eventually I'd want to use it like this:
let data = Data(base64Encoded: "aGVsbG8gd29ybGQ=")!
print(data.hexString)
I want the hexadecimal representation of a Data value in Swift.
Eventually I'd want to use it like this:
let data = Data(base64Encoded: "aGVsbG8gd29ybGQ=")!
print(data.hexString)
An alternative implementation (taken from How to crypt string to sha1 with Swift?, with an additional option for uppercase output) would be
I chose a
hexEncodedString(options:)
method in the style of the existing methodbase64EncodedString(options:)
.Data
conforms to theCollection
protocol, therefore one can usemap()
to map each byte to the corresponding hex string. The%02x
format prints the argument in base 16, filled up to two digits with a leading zero if necessary. Thehh
modifier causes the argument (which is passed as an integer on the stack) to be treated as a one byte quantity. One could omit the modifier here because$0
is an unsigned number (UInt8
) and no sign-extension will occur, but it does no harm leaving it in.The result is then joined to a single string.
Example:
The following implementation is faster by a factor about 120 (tested with 1000 random bytes). It is similar to RenniePet's solution and Nick Moore's solution, but based on UTF-16 code units, which is what Swift strings (currently) use as internal storage.
Swift 4 - From Data to Hex String
Based upon Martin R's solution but even a tiny bit faster.
Swift 4 - From Hex String to Data
I've also added a fast solution for converting a hex String into Data (based on a C solution).
Note: this function does not validate the input. Make sure that it is only used for hexadecimal strings with (an even amount of) characters.
My version. It's not as elegant, but it's about 10 times faster than the accepted answer by Martin R.
This code extends the
Data
type with a computed property. It iterates through the bytes of data and concatenates the byte's hex representation to the result:This doesn't really answer the OP's question since it works on a Swift byte array, not a Data object. And it's much bigger than the other answers. But it should be more efficient since it avoids using String(format: ).
Anyway, in the hopes someone finds this useful ...
Test case: