51

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

1

7 Answers 7

132

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)
Sign up to request clarification or add additional context in comments.

3 Comments

I don't know why I put in var buf, might as well be let buf
Definitely the best way.
Apparently not working in Swift 4. Use var buf : [UInt8] = Array(str.utf8) instead.
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)

3 Comments

[(Byte)] is not identical to to 'UInt8'
@xaxxon in what way is it not?
@JoeDaniels I have no clue. I'm not even sure I wrote that.
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]

Comments

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)")
}

Comments

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)

Comments

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.

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.