Cocoa (or to be exact the Foundation framework) has functions to swap the endianness of bytes: NSSwapInt
, NSSwapShort
, NSSwapLong
, and NSSwapLongLong
. These swap around the bytes no matter what - they make big-endian integers from small-endian integers and vice versa.
If you know which format you have there are other functions that swap it to the native endianness: NSSwapLittleIntToHost
and NSSwapBigIntToHost
. There are also the reverse functions which swap from the native format to little or big endian format: NSSwapHostIntToLittle
and NSSwapHostIntToBig
. Those are available for the other integer types and floating point types as well. What they do is they call the primitive swap functions on the values if necessary. So NSSwapLittleIntToHost
doesn’t do anything while NSSwapBigIntToHost
returns the result of NSSwapInt
on a little endian machine.
Note that these take parameters of the compilers integer types and not the NSInteger
type. So depending on wether you’re generating 32bit or 64bit code you have to use different functions if you are using NSInteger
.
You also should not cast your byte array to an integer pointer and dereference that. It would be better to assemble the integer using bit shift operations. Your code will only work if NSInteger
is 32 bit wide. If it is 64 bit then your number will be garbage or your program might even crash. But even if you are using an integer type that is always 32 bit wide (int32_t
from the C99 <stdint.h>
header for example) this might not work as expected.