Search code examples
objective-cnsdatansmutabledata

NSData bytes from integer


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.


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).