Home
Map
Convert String to Byte Array: utf8 and UInt8Converts String to a byte array with the utf8 property. Convert the UInt8 array back into a String.
Swift
This page was last reviewed on Aug 23, 2023.
String, byte array. In Swift 5.8 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. Then we can manipulate bytes. We can convert those bytes into a String.
An example. This example takes a String with value "perls" and gets its UTF8View. Then it creates a byte array from the UTF8View with an array creation statement.
Next It changes the first value in the byte array. It increments it, changing "p" to "q."
Finally The program uses an "if let" statement to create a String from the byte array. It specifies ASCII encoding.
import Foundation // An input string. let name = "perls" // Get the String.UTF8View. let bytes = name.utf8 print(bytes) // Get an array from the UTF8View. // ... This is a byte array of character data. var buffer = [UInt8](bytes) // Change the first byte in the byte array. // ... The byte array is mutable. buffer[0] = buffer[0] + UInt8(1) print(buffer) // Get a string from the byte array. if let result = String(bytes: buffer, encoding: String.Encoding(rawValue: NSASCIIStringEncoding)) { print(result) }
perls [113, 101, 114, 108, 115] qerls
Create string, bytes. It is possible to create a String from a sequence of bytes. We can specify these directly in the program. This allows dynamic creation of strings.
Here We create an empty byte array (with the UInt8 type). We add 3 UInt8 values to the array.
Result Our resulting string has the value "abc" from the bytes added to the buffer. We use ASCII encoding.
import Foundation // An empty UInt8 byte array. var buffer = [UInt8]() // Add some bytes to the byte array. buffer.append(UInt8(97)) buffer.append(UInt8(98)) buffer.append(UInt8(99)) // Get a string from the byte array. if let result = String(bytes: buffer, encoding: String.Encoding(rawValue: NSASCIIStringEncoding)) { print(result) }
abc
In Swift, Strings are hard to manipulate. Using a UInt8 array to create certain kinds of strings (like those meant for machines) is a good strategy to improve performance and gain clarity.
Some notes. In Swift we have access to a utf8 property. This is key to converting Strings to byte arrays. We use the UInt8 type to indicate a byte in this language.
Dot Net Perls is a collection of tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
This page was last updated on Aug 23, 2023 (edit).
Home
Changes
© 2007-2024 Sam Allen.