How to convert String to byte in Swift?
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)")
}
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]
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)
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)