1

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,

m4singh
  • 13
  • 5

1 Answers1

2

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

Jean
  • 7,623
  • 6
  • 43
  • 58
  • 3
    Your swap is backwards. You want to go from `host` to big endian. `Host` always represents what you have on the current device. You should also assign the raw length to a `uint16_t` variable first, then swap that variable. – rmaddy Mar 09 '13 at 00:53
  • 2
    My mistake. Most of the time I need to do the reverse, so I accepted the auto-completion in Xcode before reading the full text… Thanks for seeing it. – Jean Mar 09 '13 at 12:17