3

Are there any built in utilities or macros in the objective-c libraries for iOS that will allow you to convert bytes to and from integers with respect to endianess?

Please don't tell me to use bit-shifting operations. I am trying to avoid writing custom code to do this if it already exists.

I would like the code to convert NSData* to primitive types (int, uint, short, etc) and to convert primitive types back to NSData*.

Brian
  • 6,910
  • 8
  • 44
  • 82
  • 1
    a squillion choices here http://stackoverflow.com/questions/2182002/convert-big-endian-to-little-endian-in-c-without-using-provided-func – Warren Burton Dec 18 '11 at 15:58

2 Answers2

10

You can get the bytes from NSData by accessing the bytes property. Then just cast that to a pointer to whatever type you want. Obviously you'll need to ensure you know the endianness and size of what is in your NSData.

e.g.

#include <CFByteOrder.h>

// Bytes to uint32_t
NSData *data = <THE_DATA>;
void *bytes = [data bytes];
uint32_t *intBytes = (NSInteger*)bytes;
uint32_t swapped = CFSwapInt32BigToHost(*intBytes); ///< If the data in `data' is big endian

// uint32_t to bytes
uint32_t someInt = 1234;
uint32_t swappedInt = CFSwapInt32HostToBig(someInt); ///< If we want to store in big endian
NSData *data = [NSData dataWithBytes:&swappedInt length:sizeof(swappedInt)];
mattjgalloway
  • 34,792
  • 12
  • 100
  • 110
4

I think you want the CFSwapInt32* family of functions.

See Apple's docs.

Jesse Rusak
  • 56,530
  • 12
  • 101
  • 102
  • This takes care of the endianness part of my question, but I am still looking for some code that will go from bytes to data and the reverse. – Brian Dec 18 '11 at 16:13
  • OK, well, that part of the question wasn't there before. The other answer addresses that piece. – Jesse Rusak Dec 18 '11 at 17:12