如何在Swift中将带有十六进制数据的NSData对象转换为ASCII? [英] How do I convert an NSData object with hex data to ASCII in Swift?

查看:248
本文介绍了如何在Swift中将带有十六进制数据的NSData对象转换为ASCII?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个带有十六进制数据的NSData对象,我想将其转换为ASCII字符串.我已经看到了几个类似的问题,但是它们都在Objective-C中,并且/或者它们将字符串转换为十六进制数据,而不是相反.

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.

我发现此功能,但在Swift 2和

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
}

我不知道stride是什么,我也不知道它做什么.

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

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

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.

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

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.

希望这对某人有帮助!

这篇关于如何在Swift中将带有十六进制数据的NSData对象转换为ASCII?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆