Swift converting Byte Array into String
10,886
Solution 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)
In Swift 3 things have become much easier as a native String
can be initialized with a sequence of bytes.
let datastring = String(bytes: chars, encoding: .utf8)
However the example is not meaningful because it doesn’t represent a string so datastring
will be nil
. Use valid data like
let chars : [UInt8] = [72, 101, 108, 108, 111]
let datastring = String(bytes: chars, encoding: .utf8) // "Hello"
Solution 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)
Author by
nik
Updated on June 23, 2022Comments
-
nik almost 2 years
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.
-
Martin R almost 7 yearsSimpler:
String(bytes: chars, encoding: .utf8)
-
MarkAllen4512 over 6 years@MartinR Thanks for your answer. You should consider adding it on your own.
-
Shubham Agarwal Bhewanewala over 5 yearsIts giving string as nil. Can you tell me why??
-
Kiran Patil over 3 yearsgetting nil string. Is there any other solution?