I am facing problems while converting UInt8 Byte array to string in swift. I have searched and find a simple solution
String.stringWithBytes(buff, encoding: NSUTF8StringEncoding) but it is showing error String.type does not have a member stringWithBytes. Can anyone suggest me a solution ?
this is my code where i am getting anNSData and converted into bytes array and then i have to convert that byte array into string.
let count = data.length / sizeof(UInt8) var array = [UInt8](count: count, repeatedValue: 0) data.getBytes(&array, length:count * sizeof(UInt8)) String.stringWithBytes(buff, encoding: NSUTF8StringEncoding)
There are two ways to convert byte array to String: By using String class constructor. By using UTF-8 encoding.
A uint8_t data type is basically the same as byte in Arduino. Writers of embedded software often define these types, because systems can sometimes define int to be 8 bits, 16 bits or 32 bits long. The issue doesn't arise in C# or Java, because the size of all the basic types is defined by the language.
In Swift a byte is called a UInt8—an unsigned 8 bit integer. A byte array is a UInt8 array. In ASCII we can treat chars as UInt8 values. With the utf8 String property, we get a UTF8View collection. We can convert this to a byte array.
Update for Swift 3/Xcode 8:
String from bytes: [UInt8]:
if let string = String(bytes: bytes, encoding: .utf8) { print(string) } else { print("not a valid UTF-8 sequence") } String from data: Data:
let data: Data = ... if let string = String(data: data, encoding: .utf8) { print(string) } else { print("not a valid UTF-8 sequence") } Update for Swift 2/Xcode 7:
String from bytes: [UInt8]:
if let string = String(bytes: bytes, encoding: NSUTF8StringEncoding) { print(string) } else { print("not a valid UTF-8 sequence") } String from data: NSData:
let data: NSData = ... if let str = String(data: data, encoding: NSUTF8StringEncoding) { print(str) } else { print("not a valid UTF-8 sequence") } Previous answer:
String does not have a stringWithBytes() method. NSString has a
NSString(bytes: , length: , encoding: ) method which you could use, but you can create the string directly from NSData, without the need for an UInt8 array:
if let str = NSString(data: data, encoding: NSUTF8StringEncoding) as? String { println(str) } else { println("not a valid UTF-8 sequence") }
Swifty solution
array.reduce("", combine: { $0 + String(format: "%c", $1)}) Hex representation:
array.reduce("", combine: { $0 + String(format: "%02x", $1)})
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With