I'm trying to figure out how to "chunk" a NSData
on a specific value.
7E 55 33 22 7E 7E 22 AE BC 7E 7E AA AA 00 20 00 22 53 25 A3 4E 7E
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
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?
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];
}
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.
Swift String split() The split() method breaks up a string at the specified separator and returns an array of strings.
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
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