Search code examples
iphoneiosnsdatansmutabledata

iOS: how to add length of a NSData as its two bytes header?


I have a NSData and I would like to append its length in its header as hex digits. I am able to do this using following code:

unsigned int len = [data length];

NSMutableData *sendData = [[NSMutableData alloc] initWithBytes:&len length:2];
[sendData appendData:data];

result from above code for len = 5 is "05 00" but I want "00 05" instead. Does anyone know how to do that?

Header is always going to be of length 2.

Thanks,


Solution

  • The code below addumes (as you do) that the length is less than 65536 (two bytes). So you need to use:

    uint16_t len = CFSwapInt16HostToBig([data length]);
    NSMutableData *sendData = [[NSMutableData alloc] initWithBytes:&len length:2];
    [sendData appendData:data];
    

    The list of available function are described in de document below in the apple developer library:

    Byte-Order Utilities Reference