Question

I have an integer, with a value of 2. I append that to an NSMutableData object with:

[data appendBytes:&intVal length:2];

The number 2 is the number of bytes I want from the int. When I log the data, what I want to see is <0002> (one empty byte followed by one non-empty byte), but what I get is <0200>.

Am I missing something? The order and length of the bytes needs to be very specific. This is for a direct socket connection API. I'm not really sure what I'm doing wrong here. Maybe I'm just reading it wrong.

Thanks for the help.

Was it helpful?

Solution

Am I missing something?

Yes, the endianness of your system doesn't match what you need. Convert it to either little or big endian (the POSIX C library has functions for this purpose somewhere in the <netinet.h> or <inet.h> headers).

OTHER TIPS

NSData's description method prints it's values in hexadecimal format. This means that it needs 4 digits to represent 2 bytes, every byte may map 2^8=256 different value, every hexadecimal digit may map 16 possibile values, so 16x16x16x16 = 2^16, which is exactly what you can map with 2 bytes.

Here is the answer, It works great!

uint16_t intVal = 2;
Byte *byteData = (Byte*)malloc(2);
byteData[1] = majorValue & 0xff;
byteData[0] = (majorValue & 0xff00) >> 8;
NSData * result = [NSData dataWithBytes:byteData length:sizeof(uint16_t)];
NSLog(@"result=%@",result);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top