Luca Bartoletti
Luca Bartoletti

Reputation: 2447

NSArray and endianness

I have this piece of code

NSMutableData *mData = [NSMutableData data];

uint16_t bytes = 0x9F21;
[mData appendBytes:&bytes length:sizeof(bytes)];

When i print the bytes with p/x i get

0x9F21

If i try to po mData i get

<219f>

This is a problem related to the bytes ordering, i saw that if i convert the order of the bytes the mData stores correctly the bytes

If i print the mData object with this code i get the expected value

NSMutableData *mData = [NSMutableData data];

uint16_t bytes = CFSwapInt16HostToBig(0x9F21);
[mData appendBytes:&bytes length:sizeof(bytes)];

This is means that appendBytes require a Big endian ordering on both little and big endian archs?

Upvotes: 1

Views: 238

Answers (2)

trojanfoe
trojanfoe

Reputation: 122391

You don't say what you want to do with the data, however you should only be converting endian when reading/writing from/to external media, like network connections and files where the endian of the data is well defined. This process is called marshalling.

All the time the data is within your app, and needs to be manipulated, you need to keep the data in it's native form, which is actually treated as big-endian (i.e. doing something like bytes >> 8 will yield 0x9f).

When i print the bytes with p/x i get

0x9F21

That is printing the 16-bit unsigned integer in native format (LLDB knows it's a 16-bit type)

If i try to po mData i get

<219f>

That is printing a byte stream as that is the nature of the NSData object. It reveals that your native architecture is little-endian, however that shouldn't be important.

Upvotes: 1

slecorne
slecorne

Reputation: 1718

appendBytes will take the byte in the order they are inside the buffer pointer you give to the method. It does not require nor assume any specific endiannes order.

You have to convert your int "endianness" according to the byte order you want in NSData. Or do not use int_16 if you are only interested in bytes and store directly the bytes. It is hard to give more advice without knowledge of data to be stored.

Upvotes: 0

Related Questions