Jake Jake - 2 months ago 10x
iOS Question

How do I convert an NSData object with hex data to ASCII in Swift?

I have an

object with hex data and I want to convert it to an ASCII string. I've seen several similar questions to mine but they are all either in Objective-C and/or they convert a string into hex data instead of the other way around.

I found this function but it doesn't work in Swift 2 and the Apple documentation doesn't explain the difference between the old
and the new
(it doesn't explain stride at all):

func hex2ascii (example: String) -> String

var chars = [Character]()

for c in example.characters

let numbers = stride(from: 0, through: chars.count, by: 2).map{ // error: 'stride(from:through:by:)' is unavailable: call the 'stride(through:by:)' method instead.
strtoul(String(chars[$0 ..< $0+2]), nil, 16)

var final = ""
var i = 0

while i < numbers.count {

return final

I don't know what
is and I don't know what it does.

How do you convert hex to ASCII in Swift 2? Maybe an NSData extension...



Sorry for answering my own question, but I just (accidentally) found an amazing solution to my problem and hopefully this will help someone.

If you have an NSData object with a hex representation of an ASCII string, then all you have to do is write String(data: theNSDataObject, encoding: NSUTF8StringEncoding) and that is the ASCII string.

Hope this helps someone!