[英]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. 我有一个带有十六进制数据的
NSData
对象,我想将其转换为ASCII字符串。 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. 我已经看到了几个类似的问题,但它们都在Objective-C中,并且/或者它们将字符串转换为十六进制数据,而不是相反。
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): 我发现了此功能,但在Swift 2中不起作用, Apple文档也无法解释旧
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[$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. 我不知道
stride
是多少,也不知道它的作用。
How do you convert hex to ASCII in Swift 2? 如何在Swift 2中将十六进制转换为ASCII? Maybe an NSData extension...
也许是NSData扩展...
Thanks! 谢谢!
try: 尝试:
let asciiString = String(data: data, encoding: NSASCIIStringEncoding)
print(asciiString)
In swift 2.0 stride became a method on Int rather than a standalone method so now you do something like 在Swift 2.0中,跨步已成为Int上的方法,而不是独立的方法,因此您现在可以执行类似
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
}
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. 如果您有一个用ASCII字符串的十六进制表示形式的NSData对象,那么您要做的就是写
String(data: theNSDataObject, encoding: NSUTF8StringEncoding)
,这就是ASCII字符串。
Hope this helps someone! 希望这对某人有帮助!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.