Search code examples
iosobjective-cnsdataendianness

Changing NSData byte order to little endian


I am trying to figure out the best way to change the byte order of my NSData object that I have.

This is how I create it

NSData *pillowData = [manufData subdataWithRange:NSMakeRange(5, 4)];

This is the output of pillowData

41543138

This is what i want pillowData to be after conversion.

38315441

Essentially converting to little endian.


Solution

  •     NSData *manufData = [NSData dataWithBytes:"12345AT18" length:9];
        NSMutableData *pillowData = [[manufData subdataWithRange:NSMakeRange(5, 4)] mutableCopy];
        uint32_t *bytes = pillowData.mutableBytes;
        *bytes = CFSwapInt32(*bytes);
        NSLog(@"%@", pillowData);
    

    Output:

    2018-01-25 15:52:39.067805-0600 test[23520:1338453] <38315441>
    

    Note that this doesn't change the contents of manufData. It only changes the copy of the bytes in pillowData.