Showing posts with label NSMutableData appendBytes length example. Show all posts
Showing posts with label NSMutableData appendBytes length example. Show all posts

Saturday, June 1, 2013

NSMutableData appendBytes length example in Objective C (iOS).


NSMutableData appendBytes length

Appends to the receiver a given number of bytes from a given buffer.

- (void)appendBytes:(const void *)bytes length:(NSUInteger)length

Parameters
bytes
A buffer containing data to append to the receiver's content.
length
The number of bytes from bytes to append.

Discussion of [NSMutableData appendBytes length]
A sample using this method can be found in Working With Mutable Binary Data.

NSMutableData appendBytes length example.
For example, to convert from host (your machine) to network endianness, use htonl():

uint32_t theInt = htonl((uint32_t)myInteger);
[myData appendBytes:&theInt length:sizeof(theInt)];

Example of [NSMutableData appendBytes length].
NSMutableData *data = [NSMutableData data];
char bytesToAppend[5] = {0x01, 0xf0, 0x64, 0x0, 0x6a};
[data appendBytes:bytesToAppend length:sizeof(bytesToAppend)];

NSMutableData appendBytes length example.
To store:

SInt16 *frames = ...;
NSUInteger length = ...;    // Assuming number of elements in frames, not bytes!  
NSMutableData *data = [[NSMutableData alloc] initWithCapacity:0];
[data appendBytes:(const void *)frames length:length * sizeof(SInt16)];
To retrieve:

SInt16 *frames = (SInt16 *)[data bytes];
NSUInteger length = [data length] / sizeof(SInt16);

End of NSMutableData appendBytes length example article.