How to convert Data to/from Hexa decimal string in the swift code example

This tutorial explains about following things in Swift

  • Convert Data to Hexa decimal String
  • Hexadecimal String to Data with example

Sometimes, We need to convert Data to/from Hexa string in Swift.

Data contains a string representation of bytes Hexa is a string that contains 0 to 9 and a to g.

How to convert Data to Hexa decimal String in swift

In this example, Convert data to a Hexa decimal string

  • First create a string variable
  • Convert this to a data object using a Data constructor
  • It prints the data in bytes
  • call the map function on the data object, which returns hexa value

Here is an example

import Foundation
let str = "onetwothree"
let data = Data(str.utf8)
print(data) // 11 bytes

let hexaValue = data.map{ String(format:"%02x", $0) }.joined()
print(hexaValue) // 6f6e6574776f7468726565

Output:

11 bytes
6f6e6574776f7468726565

Convert Hexa decimal string to Data in Swift

In this example, Convert the Hexa decimal string to a Data object using the Data constructor with the hexString attribute

Here is a code example

    let dataObject = Data(hexString: "abc11d")
    print(dataObject?.hexString) //  Optional("abc11d")

It is an easy and quick way to convert Hexa to data

Conclusion

Learned how to convert data to Hexa and Hexa decimal to Data in swift with code examples