NikkyD
NikkyD

Reputation: 2284

Can i define in what endianess i read from NSData?

I have some files written on an Android device, it wrote bytes in big endian. Now i try to read this file with iOS and there i need them in small endian.

I can make a for loop and

int temp;
for(...) {
  [readFile getBytes:&temp range:NSMakeRange(offset, sizeof(int))];
  target_array[i] = CFSwapInt32BigToHost(temp);
  // read more like that
}

However it feels silly to read every single value and turn it before i can store it. Can i tell the NSData that i want the value read with a certain byte-order so that i can directly store it where it should be ?

(and save some time, as the data can be quite large)

I also worry about errors when some datatype changes and i forget to use the 16 instead of the 32 swap.

Upvotes: 1

Views: 338

Answers (1)

rmaddy
rmaddy

Reputation: 318824

No, you need to swap every value. NSData is just a series of bytes with no value or meaning. It is your app that understands the meaning so it is your code logic that must swap each set of bytes as needed.

The data could be filled with all kinds of values of different sizes. 8-bit values, 16-bit values, 32-bit values, etc. as well as string data or just a stream of bytes that don't need any ordering at all. And the NSData can contain any combination of these values.

Given all of this, there is no simple way to tell NSData that the bytes need to be treated in a specific endianness.

If your data is, for example, nothing but 32-bit integer values stored in a specific endianness and you want to extract an array of bytes, create a helper class that does the conversion.

Upvotes: 1

Related Questions