3

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.

3
  • Sorry its typo mistake.. now I updated the question Commented Feb 25, 2016 at 7:07
  • 1
    Do you get any errors? Is that really UTF-8? Commented Feb 25, 2016 at 7:20
  • Which version of Swift are you using? Commented Feb 25, 2016 at 7:43

3 Answers 3

6

[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"
Sign up to request clarification or add additional context in comments.

Comments

4

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)

5 Comments

Simpler: String(bytes: chars, encoding: .utf8)
@MartinR Thanks for your answer. You should consider adding it on your own.
Its giving string as nil. Can you tell me why??
getting nil string. Is there any other solution?
getting nil string as well.
0

let str = String(decoding: chars, as: UTF8.self) - changes wrong byts by 0xfffd let str = chars.map { String(UnicodeScalar($0)) }.joined()

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.