Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift: How to convert a String to UInt8 array?

Tags:

swift

How do you convert a String to UInt8 array?

var str = "test" var ar : [UInt8] ar = str 
like image 716
Andrey Zet Avatar asked May 15 '15 08:05

Andrey Zet


People also ask

What is UInt8 Swift?

An 8-bit unsigned integer value type.


2 Answers

Lots of different ways, depending on how you want to handle non-ASCII characters.

But the simplest code would be to use the utf8 view:

let string = "hello"  let array: [UInt8] = Array(string.utf8) 

Note, this will result in multi-byte characters being represented as multiple entries in the array, i.e.:

let string = "é" print(Array(string.utf8)) 

prints out [195, 169]

There’s also .nulTerminatedUTF8, which does the same thing, but then adds a nul-character to the end if your plan is to pass this somewhere as a C string (though if you’re doing that, you can probably also use .withCString or just use the implicit conversion for bridged C functions.

like image 52
Airspeed Velocity Avatar answered Oct 04 '22 19:10

Airspeed Velocity


let str = "test" let byteArray = [UInt8](str.utf8) 
like image 32
Michael Dorner Avatar answered Oct 04 '22 19:10

Michael Dorner