Question

How would I go about appending this binary string

111000111000111111000111000111

to an NSMutableData object that contains a png (NSMutableData *dataForPNGFile = UIImagePNGRepresentation(p.Image);)

Was it helpful?

Solution

You'd need to parse the string into an NSData, then append that.

I'm not aware of anything built in, so e.g.

NSMutableData *data = [NSMutableData dataWithLength(string.length+7)/8];
uint8_t *mutableBytes = (uint8_t *)data.mutableBytes;

for(NSUinteger index = 0; index < string.length; index++)
{
    unichar character = [string characterAtIndex:index];
    mutableBytes[index >> 3] <<= 1;
    if(character == '1') mutableBytes[index >> 3] |= 1;
}

if(string.length&7)
    mutableBytes[string.length >> 3] <<= (7 - (string.length&7));

So assumptions are that your source string is only 1s and 0s, that it's written from most significant to least significant digit and that it's byte rather than word oriented.

Also, UIImagePNGRepresentation returns immutable data so you'll need to take a mutable copy of that.

OTHER TIPS

Look at the NSMuteableData method appendBytes:length:

You will have to convert your bits to bytes as @Tommy says.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top