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);
}
EDIT_001
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
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.)
Have you found
Endian.h
OSByteOrder.h
精彩评论