51

How to convert String to byte in Swift? Like String .getBytes()in Java.

Leo Dabus
  • 229,809
  • 59
  • 489
  • 571
YuXuan Fu
  • 1,911
  • 3
  • 14
  • 13
  • possible duplicate of [How to convert NSString to bytes](http://stackoverflow.com/questions/881482/how-to-convert-nsstring-to-bytes) – ahruss Jul 30 '14 at 02:31

7 Answers7

128

There is a more elegant way.

Swift 3:

let str = "Hello"
let buf = [UInt8](str.utf8)

Swift 4: (thanks to @PJ_Finnegan)

let str = "Hello"
let buf: [UInt8] = Array(str.utf8)
derpoliuk
  • 1,756
  • 2
  • 27
  • 43
Albin Stigo
  • 2,082
  • 2
  • 17
  • 14
18

You can iterate through the UTF8 code points and create an array:

var str = "hello, world"
var byteArray = [Byte]()
for char in str.utf8{
    byteArray += [char]
}
println(byteArray)
Connor Pearson
  • 63,902
  • 28
  • 145
  • 142
13

edit/update: Xcode 11.5 • Swift 5.2

extension StringProtocol {
    var data: Data { .init(utf8) }
    var bytes: [UInt8] { .init(utf8) }
}

"12345678".bytes   // [49, 50, 51, 52, 53, 54, 55, 56]
Leo Dabus
  • 229,809
  • 59
  • 489
  • 571
3

String.withCString is the peer to Java's String.getBytes(void). Use it like this (extra typing added):

let s = "42"
s.withCString {
  ( bytes : (UnsafePointer<CChar>) ) -> Void in
  let k = atoi(bytes)
  println("k is \(k)")
}
hnh
  • 13,957
  • 6
  • 30
  • 40
2

Another option, for when you need to be able to pass to C-library functions:

let str = hexColour.cStringUsingEncoding(NSUTF8StringEncoding)
let x = strtol(str!, nil, 16)
Chris
  • 39,719
  • 45
  • 189
  • 235
1

string.utf8 or string.utf16 should do something like what you are asking for. See here for more info: https://developer.apple.com/library/prerelease/ios/documentation/Swift/Conceptual/Swift_Programming_Language/StringsAndCharacters.html.

carloabelli
  • 4,289
  • 3
  • 43
  • 70
1

Swift 4.1.

It depends what you want to achieve. For the same question, I used...

let message = "Happy"
for v in message.utf8 {
    print(v)
}

I then performed the operations I needed on the individual byte. The output is:

//72
//97
//112
//112
//121

https://developer.apple.com/documentation/swift/string.utf8view

rustyMagnet
  • 3,479
  • 1
  • 31
  • 41