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.
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.
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.
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.
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.
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
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