26

All I am looking to do is take a string and get its hex value. I've been following this post. Here is the code I have in my playground:

let str = "Say Hello to My Little Friend"
let data = str.data(using: String.Encoding.utf16)
print("\(data!)")

However, my code just prints:

"60 bytes\n"

How can I print the hex value? For reference, it should be:

5361792048656c6c6f20746f204d79204c6974746c6520467269656e64
stkent
  • 19,772
  • 14
  • 85
  • 111
user481610
  • 3,230
  • 4
  • 54
  • 101

2 Answers2

55

Since Data is a Sequence of UInt8, you could map each byte to a string and then join them:

data.map { String(format: "%02x", $0) }.joined()
kennytm
  • 510,854
  • 105
  • 1,084
  • 1,005
  • 2
    I like this better than the accepted answer because it gives the programmer complete control of the output format. – JeremyP Oct 17 '16 at 14:31
  • 2
    var dataMap = data.map { String(format: "%02x", $0)}.joined(); print("\(dataMap)") – utarid Jul 29 '18 at 15:51
36

Just

print(data! as NSData)

PS: Your expected hex is .utf8

vadian
  • 274,689
  • 30
  • 353
  • 361