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,

有帮助吗?

解决方案

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

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top