Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save pokeb/287820 to your computer and use it in GitHub Desktop.
Save pokeb/287820 to your computer and use it in GitHub Desktop.
- (void)demonstrateCustomBinaryDataParsing
{
// Generate data in the format:
// name:size\n<data>name:size\n<data>
NSData *file1data = [NSData dataWithContentsOfFile:@"/Users/ben/Desktop/1.png"];
NSData *file2data = [NSData dataWithContentsOfFile:@"/Users/ben/Desktop/2.png"];
NSMutableData *payload = [NSMutableData data];
NSLog([NSString stringWithFormat:@"file1:%lu\n",[file1data length]]);
[payload appendData:[[NSString stringWithFormat:@"file1:%lu\n",[file1data length]] dataUsingEncoding:NSASCIIStringEncoding]];
[payload appendData:file1data];
[payload appendData:[[NSString stringWithFormat:@"file2:%lu\n",[file2data length]] dataUsingEncoding:NSASCIIStringEncoding]];
[payload appendData:file2data];
// Parse the data to get the files back out
const char *bytes = [payload bytes];
unsigned int length = [payload length];
unsigned int lastHeaderStartByte = 0;
NSMutableArray *files = [NSMutableArray array];
NSMutableDictionary *currentFile = [NSMutableDictionary dictionary];
unsigned int readByte = 0;
while (readByte < length) {
if (bytes[readByte] == *"\n") {
void *header = calloc(readByte+1-lastHeaderStartByte,1);
[payload getBytes:header range:NSMakeRange(lastHeaderStartByte,readByte)];
NSArray *headerStringArray = [[NSString stringWithCString:header encoding:NSASCIIStringEncoding] componentsSeparatedByString:@":"];
[currentFile setObject:[headerStringArray objectAtIndex:0] forKey:@"name"];
unsigned long long length = [[headerStringArray objectAtIndex:1] longLongValue];
free(header);
char *data = malloc(length);
[payload getBytes:data range:NSMakeRange(readByte+1,length)];
[currentFile setObject:[NSData dataWithBytes:data length:length] forKey:@"data"];
lastHeaderStartByte = readByte+1+length;
readByte = lastHeaderStartByte;
free(data);
[files addObject:currentFile];
currentFile = [NSMutableDictionary dictionary];
}
readByte++;
}
UIImage *image = [UIImage imageWithData:[[files objectAtIndex:0] objectForKey:@"data"]];
UIImage *image2 = [UIImage imageWithData:[[files objectAtIndex:1] objectForKey:@"data"]];
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment