Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swapping Endianness In Objective-C?

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

like image 339
fuzzygoat Avatar asked Dec 10 '09 21:12

fuzzygoat


People also ask

What is swap Endianness?

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.

What is __ builtin_bswap32?

__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.

What is big endian and little endian?

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.

What is little endian?

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).


2 Answers

As well as the APIs already mentioned, there is CoreFoundation/CFByteOrder.h.

like image 128
Stephen Canon Avatar answered Nov 13 '22 13:11

Stephen Canon


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.)

like image 25
Michael Avatar answered Nov 13 '22 12:11

Michael