如何将具有十六进制数据的 NSData 对象转换为 Swift 中的 ASCII?

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

我有一个包含十六进制数据的 NSData 对象,我想将其转换为 ASCII 字符串。我见过几个与我类似的问题,但它们都在 Objective-C and/or 中,它们将字符串转换为十六进制数据,而不是相反。

我发现 but it doesn't work in Swift 2 and the Apple documentation 没有解释旧的 stride 和新的 stride 之间的区别(它根本没有解释步幅):

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[[=11=] ..< [=11=]+2]), nil, 16)
    }

    var final = ""
    var i = 0

    while i < numbers.count {
        final.append(Character(UnicodeScalar(Int(numbers[i]))))
        i++
    }

    return final
}

我不知道 stride 是什么,也不知道它的作用。

如何在 Swift 2 中将十六进制转换为 ASCII?也许是 NSData 扩展...

谢谢!

在 swift 2.0 中,stride 变成了 Int 上的一个方法而不是一个独立的方法,所以现在你可以做类似

的事情
0.stride(through: 10, by: 2)

所以现在您发布的代码应该是:

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[[=11=] ..< [=11=]+2]), nil, 16)
    }

    var final = ""
    var i = 0

    while i < numbers.count {
        final.append(Character(UnicodeScalar(Int(numbers[i]))))
        i++
    }

    return final
}

很抱歉回答我自己的问题,但我只是(无意中)找到了解决我问题的绝妙方法,希望这会对某人有所帮助。

如果您有一个 NSData 对象,其中包含 ASCII 字符串的十六进制表示,那么您所要做的就是编写 String(data: theNSDataObject, encoding: NSUTF8StringEncoding),这就是 ASCII 字符串。

希望这对某人有所帮助!

尝试:

let asciiString = String(data: data, encoding: NSASCIIStringEncoding)
print(asciiString)