Swift converting Byte Array into String

2019-08-12 14:33发布

问题:

I can't convert this below byte array into String in swift.

    let chars: [UInt8] =  [255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 0, 0, 0, 0]

let datastring = NSString(data: chars, encoding: NSUTF8StringEncoding)

But in android it just works fine I don't know whats wrong in swift.

回答1:

[UInt8] is not NSData, so you can't use the NSString(data... initializer

You might use

let chars: [UInt8] =  [255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 0, 0, 0]
let count = chars.count / sizeof(UInt8)
let datastring = NSString(bytes: chars, length: count, encoding: NSASCIIStringEncoding)


回答2:

In Swift 3 you can use this:

import Foundation
let chars: [UInt8] =  [255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 0, 0, 0, 0]
let string = String(data: Data(chars), encoding: .utf8)