I need to swap the endianness of some values and just wondered if there was anything available in Objective-C, currently I am swapping the bytes with the CStyle function below (which obviously I can reuse) I just wanted to check there was nothing specific I was missing?
float floatFlip(float inFloat) {
union {
int intValue;
float newFloat;
} inData, outData;
inData.newFloat = inFloat;
outData.intValue = CFSwapInt32BigToHost(inData.intValue);
return(outData.newFloat);
}
Thanks to the pointers here I have integers sorted, whats the simplest way to swap a float?
int myInteger = CFSwapInt32BigToHost(myInteger);
(Code above updated)
float myFloat = floatFlip(myFloat);
gary
The SWAP_ENDIAN function reverses the byte ordering of arbitrary scalars, arrays or structures. It can make “big endian” number “little endian” and vice-versa.
__builtin_bswap32() is used to reverse bytes (it's used for littel/big endian issues (from gcc)). htonl() is used to reverse bytes too (conversion from host to network). I checked both functions and they returns the same result.
Big-endian is an order in which the "big end" (most significant value in the sequence) is stored first, at the lowest storage address. Little-endian is an order in which the "little end" (least significant value in the sequence) is stored first.
Specifically, little-endian is when the least significant bytes are stored before the more significant bytes, and big-endian is when the most significant bytes are stored before the less significant bytes. When we write a number (in hex), i.e. 0x12345678 , we write it with the most significant byte first (the 12 part).
As well as the APIs already mentioned, there is CoreFoundation/CFByteOrder.h.
You're looking for OSSwapInt32()
(or OSSwapInt16()
, OSSwapInt64()
, etc.). See OSByteOrder.h.
Also note that these are non-portable. If you are only converting to big-endian you may want to consider using something like htonl()
, which is included in the standard library <arpa/inet.h>
. (Unfortunately, though, there is no standard library for simply swapping back-and-forth.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With