47

How do you convert a String to UInt8 array?

var str = "test"
var ar : [UInt8]
ar = str
vacawama
  • 150,663
  • 30
  • 266
  • 294
Andrey Zet
  • 556
  • 1
  • 5
  • 8

4 Answers4

78

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.

Airspeed Velocity
  • 40,491
  • 8
  • 113
  • 118
13
let str = "test"
let byteArray = [UInt8](str.utf8)
Michael Dorner
  • 17,587
  • 13
  • 87
  • 117
4

swift 4

 func stringToUInt8Array(){

     let str:String = "Swift 4"
     let strToUInt8:[UInt8] = [UInt8](str.utf8)

     print(strToUInt8)
 }
Deepak Tagadiya
  • 2,187
  • 15
  • 28
0

I came to this question looking for how to convert to a Int8 array. This is how I'm doing it, but surely there's a less loopy way:

Method on an Extension for String

public func int8Array() -> [Int8] {
    var retVal : [Int8] = []
    for thing in self.utf16 {
        retVal.append(Int8(thing))
    }
    return retVal
}

Note: storing a UTF-16 encoded character (2 bytes) in an Int8 (1 byte) will lead to information loss.

Dan Rosenstark
  • 68,471
  • 58
  • 283
  • 421
  • 2
    shouln't you use Int16 for utf16? – marosoaie Mar 09 '17 at 09:26
  • @marosoaie that would be good too. Depends what you're trying to get to. Surprisingly, INT8_MAX is only 127, which is a number that I've heard of and used before, so that's pretty scary. I'd probably just opt for `Int` if I had a choice and let iOS sort it out. – Dan Rosenstark Mar 14 '17 at 19:37
  • 3
    The problem is that int8 is 1 byte, and utf16 characters are 2 bytes. Storing one utf16 character in a int8 is going to lead losing information and data corruption. – marosoaie Mar 14 '17 at 19:50