Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert String to byte in Swift?

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

like image 382
YuXuan Fu Avatar asked Jul 30 '14 02:07

YuXuan Fu


People also ask

How to convert String to bytes in Swift?

Use var buf : [UInt8] = Array(str. utf8) instead.

What is byte array in Swift?

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.

How do you split bytes?

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.

Can you slice bytes in Python?

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.


2 Answers

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) 
like image 77
Albin Stigo Avatar answered Oct 03 '22 06:10

Albin Stigo


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) 
like image 37
Connor Avatar answered Oct 03 '22 08:10

Connor