Search code examples
iosstringswifthexnsdata

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


I have an NSData 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 stride and the new stride (it doesn't explain stride at all):

func hex2ascii (example: String) -> String
{

    var chars = [Character]()

    for c in example.characters
    {
        chars.append(c)
    }

    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 {
        final.append(Character(UnicodeScalar(Int(numbers[i]))))
        i++
    }

    return final
}

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

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

Thanks!


Solution

  • 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!