How to convert String to byte in Swift? Like String .getBytes()
in Java.
Use var buf : [UInt8] = Array(str. utf8) instead.
In Swift a byte is called a UInt8—an unsigned 8 bit integer. A byte array is a UInt8 array. In ASCII we can treat chars as UInt8 values. With the utf8 String property, we get a UTF8View collection. We can convert this to a byte array.
Solution: To split a byte string into a list of lines—each line being a byte string itself—use the Bytes. split(delimiter) method and use the Bytes newline character b'\n' as a delimiter.
We can slice bytearrays. And because bytearray is mutable, we can use slices to change its contents. Here we assign a slice to an integer list.
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)
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With