2

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!

Community
  • 1
  • 1
Jake
  • 319
  • 1
  • 7
  • 21

3 Answers3

6

try:

let asciiString = String(data: data, encoding: NSASCIIStringEncoding)
print(asciiString)
gammachill
  • 1,466
  • 1
  • 13
  • 14
  • 1
    I like this answer as an option because it was successfully able to handle a situation in which the solution selected by Jake //namely: `String(data: theNSDataObject, encoding: NSUTF8StringEncoding)` // was generating output that sometimes failed a screen for "valid" utf-8 sequences when I only needed ascii characters. Note: Swift 3.0.2, Xcode 8.2, prefers (instead of encoding: NSASCIIStringEncoding): `let asciiString = String(data: data, encoding: String.Encoding.ascii)` – Cam U Aug 27 '17 at 08:54
1

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!

Jake
  • 319
  • 1
  • 7
  • 21
0

In swift 2.0 stride became a method on Int rather than a standalone method so now you do something like

0.stride(through: 10, by: 2)

So now the code you posted should be:

func hex2ascii (example: String) -> String {
    var chars = [Character]()

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

    let numbers =  0.stride(through: chars.count, by: 2).map{
        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
}
tbondwilkinson
  • 1,067
  • 2
  • 8
  • 16