我有一個NSData
對象與十六進制數據,我想將其轉換爲ASCII字符串。我見過幾個類似的問題,但它們都在Objective-C中,並且/或者它們將字符串轉換爲十六進制數據而不是其他方式。如何在Swift中將十六進制數據的NSData對象轉換爲ASCII?
我發現this function但它不會在雨燕2工作和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[$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
是什麼,我不知道它是什麼。
如何在Swift 2中將十六進制轉換爲ASCII?也許一個NSData擴展...
謝謝!
我喜歡這個答案作爲一個選項,因爲它是能夠成功地處理中選擇由傑克的解決方案的情況//即:'字符串(data:theNSDataObject,編碼:NSUTF8StringEncoding) ''當我只需要ascii字符時,//產生的輸出有時會失敗「valid」utf-8序列的屏幕。注意:Swift 3.0.2,Xcode 8.2,更喜歡(而不是編碼:NSASCIIStringEncoding):'let asciiString = String(data:data,encoding:String.Encoding.ascii)' –