Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Splitting or Chunking NSData on specific value(s) in swift

Tags:

ios

swift

nsdata

I'm trying to figure out how to "chunk" a NSData on a specific value.

Input Data

7E 55 33 22 7E 7E 22 AE BC 7E 7E AA AA 00 20 00 22 53 25 A3 4E 7E

Output Data

Returns an array of 3 elements of type [NSData] where the elements are:

  • 55 33 22
  • 22 AE BC
  • AA AA 00 20 00 22 53 25 A3 4E

Where I'm at

I know I can do something like:

var ptr = UnsafePointer<UInt8>(data.bytes)
var bytes = UnsafeBufferPointer<UInt8>(start: ptr, count: data.length)

And I guess iterate through doing a comparison similar to:

bytes[1] == UInt8(0x7E)

And I guess build up "ranges" but I was wondering if there is a better way to go about this?

Code Stub

private fund chunkMessage(data: NSData) -> [NSData] {
  var ptr = UnsafePointer<UInt8>(data.bytes)
  var bytes = UnsafeBufferPointer<UInt8>(start: ptr, count: data.length)
  var ret = []

 // DO SOME STUFF

  return ret as! [NSData];

}
like image 534
Jeef Avatar asked Mar 24 '15 15:03

Jeef


People also ask

How do you split a string after a specific character in Swift?

To split a String by Character separator in Swift, use String. split() function. Call split() function on the String and pass the separator (character) as argument. split() function returns a String Array with the splits as elements.

How do I separate words in a string Swift?

Swift String split() The split() method breaks up a string at the specified separator and returns an array of strings.


1 Answers

I ran into a similar situation but I just wanted to chunk my data by specific sizes, here's how I got it to work in swift 2.0. This assumes that "data" is of type NSData and is already filled with the info you want to split:

    let length = data.length
    let chunkSize = 1048576      // 1mb chunk sizes
    var offset = 0

    repeat {
        // get the length of the chunk
        let thisChunkSize = ((length - offset) > chunkSize) ? chunkSize : (length - offset);

        // get the chunk
        let chunk = data.subdataWithRange(NSMakeRange(offset, thisChunkSize))

        // -----------------------------------------------
        // do something with that chunk of data...
        // -----------------------------------------------

        // update the offset
        offset += thisChunkSize;

    } while (offset < length);

Hope it helps someone

like image 169
adan1985 Avatar answered Sep 19 '22 10:09

adan1985