Swift: Bytes for Beginners (Part I)

Talk of buffers and bytes can be quite daunting and before you know it people are wanting you to XOR. But the code that I'm going to post in this series is going to move slowly. First of all we're going to start with a string:
var str = "Hello, playground"
You should be comfortable with this first of all. Next we're going to create a buffer. Don't run away. A buffer is simply an array. And our buffer is going to be an array of unsigned 8-bit integers:
var buff = [UInt8]()


Why unsigned 8-bit ints? Well these are the code units that a UTF8-encoded string works with. So that's the only thing we can use for this example.

But how do we know the string is UTF8-encoded? It isn't yet, but we're going to extract the utf8 bytes and then append them to our buffer (array) like this:
buff += str.utf8
Painless. Next let's transform those bytes back into a string for completeness:
String.stringWithBytes(buff, encoding: NSUTF8StringEncoding)
A String (or rather NSString) method is used to create a string using a byte buffer and we've told the method the encoding so that it knows how to transform the unsigned 8-bit ints into a string.

For completeness, here's everything for you to cut and paste into a playground:
var str = "Hello, playground"
var buff = [UInt8]()
buff += str.utf8

// You now have a buffer loaded with bytes!!
// A byte buffer is simply an array of bytes, and the bytes are simply numbers. Nothing to be scared of.

String.stringWithBytes(buff, encoding: NSUTF8StringEncoding)

// The bytes have now been transformed back into a string!!
// Mission accomplished.

Next time we'll concatenate two sets of bytes and probably do some other stuff too. Stay tuned.

Comments

  1. Use this instead:

    String(bytes:buff, encoding:NSUTF8StringEncoding)

    ReplyDelete
  2. Great little tutorial. Thanks!

    Swift 4:

    String(bytes:buff, encoding: String.Encoding.utf8)

    ReplyDelete

Post a Comment