0
votes

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.

3
Are you aware that sizeof(int) may be different from 2?Ramy Al Zuhouri
try to dig yourself in the difference between the low-endian, big-endian representation, maybe it will help you.holex
sizeof(int) in this case is definitely bigger than 2 (it's 4). However, the api I'm using required this particular part of the packet be only 2 bytes long.btomw

3 Answers

2
votes

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

0
votes

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.

0
votes

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