Cocoa (or rather, the framework) has functions for replacing bytes of bytes: NSSwapInt , NSSwapShort , NSSwapLong and NSSwapLongLong . They exchange bytes regardless of what they make big-endian integers from small numbers and vice versa.
If you know what format you have, there are other functions that change it to an internal entity: NSSwapLittleIntToHost and NSSwapBigIntToHost . There are also inverse functions that change from native format to small or large format: NSSwapHostIntToLittle and NSSwapHostIntToBig . They are available for other integer types and floating point types. What they do, they are called primitive swap functions for values, if necessary. Thus, NSSwapLittleIntToHost does nothing, and NSSwapBigIntToHost returns the result of NSSwapInt on the small destination machine.
Note that they take parameters of integer types of compilers, not of type NSInteger . Therefore, depending on whether you are creating 32-bit or 64-bit code, you need to use different functions if you use NSInteger .
You should also not drop an array of bytes onto an integer pointer and cast it. It would be better to collect an integer using bit shift operations. Your code will only work if NSInteger is 32 bits wide. If it is 64 bits, then your number will be garbage or your program may even crash. But even if you use an integer type that always has a width of 32 bits ( int32_t from the header C99 <stdint.h> , for example), this may not work as expected.
Sven
source share