문제

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