Last active
September 23, 2019 19:28
-
-
Save lzell/c0747a18742ca2dd59bfb969ce35e768 to your computer and use it in GitHub Desktop.
Swift string to data (bytes) and back
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// (string, swift, bytes, data, buffer, cstring) | |
print("--- using nulTerminated ---") | |
let x : String = "hello" | |
let buf = x.nulTerminatedUTF8 | |
print(buf) | |
print("\n--- using [UInt8] ---") | |
let buf2 : [UInt8] = [UInt8](x.utf8) | |
print(buf2) | |
print("\n--- returning to string ---") | |
// Now for the other direction, as far as I can tell we need Foundation: | |
import Foundation | |
print(String(bytes: buf, encoding: NSUTF8StringEncoding)) | |
print(String(bytes: buf2, encoding: NSUTF8StringEncoding)) | |
// Notice that the first buf has an extra \0 in the string. Apparently the | |
// String(bytes:encoding:) initialializer does not want a nul terminated UInt8 | |
// array. Can we print buffer directly as a UTF8 encoded string? Yes! | |
let ptr = x.nulTerminatedUTF8.withUnsafeBufferPointer {$0} | |
print(String.fromCString(UnsafePointer<Int8>(ptr.baseAddress))) | |
print("\n--- using NSData --- ") | |
// Getting NSData: | |
let data = x.dataUsingEncoding(NSUTF8StringEncoding)! | |
// Getting byte array: | |
let uint8Rep = [UInt8](UnsafeBufferPointer(start: UnsafePointer<UInt8>(data.bytes), count: data.length)) | |
print(uint8Rep) | |
// Getting back to String: | |
print(String(data: data, encoding: NSUTF8StringEncoding)) | |
// Getting back to String using byte array: | |
print(String(bytes: uint8Rep, encoding: NSUTF8StringEncoding)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment