Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift 3 method to create utf8 encoded Data from String

I know there's a bunch of pre Swift3 questions regarding NSData stuff. I'm curious how to go between a Swift3 String to a utf8 encoded (with or without null termination) to Swift3 Data object.

The best I've come up with so far is:

let input = "Hello World" let terminatedData = Data(bytes: Array(input.nulTerminatedUTF8)) let unterminatedData = Data(bytes: Array(input.utf8)) 

Having to do the intermediate Array() construction seems wrong.

like image 606
Travis Griggs Avatar asked Jun 17 '16 20:06

Travis Griggs


People also ask

How do I convert string to UTF?

In order to convert a String into UTF-8, we use the getBytes() method in Java. The getBytes() method encodes a String into a sequence of bytes and returns a byte array. where charsetName is the specific charset by which the String is encoded into an array of bytes.

What is UTF-8 encoding in Swift?

UTF8View Elements Match Encoded C Strings When you call a C function using a String , Swift automatically creates a buffer of UTF-8 code units and passes a pointer to that buffer. The code units of that buffer match the code units in the string's utf8 view.

What is string encoding in Swift?

A string is a series of characters, such as "Swift" , that forms a collection. Strings in Swift are Unicode correct and locale insensitive, and are designed to be efficient. The String type bridges with the Objective-C class NSString and offers interoperability with C functions that works with strings.

What UTF-8 means?

UTF-8 (UCS Transformation Format 8) is the World Wide Web's most common character encoding. Each character is represented by one to four bytes. UTF-8 is backward-compatible with ASCII and can represent any standard Unicode character.


1 Answers

It's simple:

let input = "Hello World" let data = input.data(using: .utf8)! 

If you want to terminate data with null, simply append a 0 to it. Or you may call cString(using:)

let cString = input.cString(using: .utf8)! // null-terminated 
like image 167
Code Different Avatar answered Sep 19 '22 16:09

Code Different