Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting float values from big endian to little endian

Tags:

Is it possible to convert floats from big to little endian? I have a big endian value from a PowerPC platform that I am sendING via TCP to a Windows process (little endian). This value is a float, but when I memcpy the value into a Win32 float type and then call _byteswap_ulongon that value, I always get 0.0000?

What am I doing wrong?

like image 259
Blade3 Avatar asked May 06 '10 16:05

Blade3


People also ask

How are floats stored in 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.

Are floats stored in big-endian?

Integers and floating-point numbers don't care about endianness; they're just multi-byte values. Likewise, endianness doesn't care about whether it's an int or a float. It just stores the bytes in a particular order. @HansPassant "The 4 bytes are just stored in reverse order.

Is IEEE 754 Little endian?

Because there have been many floating-point formats with no network standard representation for them, the XDR standard uses big-endian IEEE 754 as its representation.

What is endian swap?

In little-endian style, the bytes are written from left to right in increasing significance. In big-endian style, the bytes are written from left to right in decreasing significance. The swapbytes function swaps the byte ordering in memory, converting little endian to big endian (and vice versa).


2 Answers

simply reverse the four bytes works

float ReverseFloat( const float inFloat ) {    float retVal;    char *floatToConvert = ( char* ) & inFloat;    char *returnFloat = ( char* ) & retVal;     // swap the bytes into a temporary buffer    returnFloat[0] = floatToConvert[3];    returnFloat[1] = floatToConvert[2];    returnFloat[2] = floatToConvert[1];    returnFloat[3] = floatToConvert[0];     return retVal; } 
like image 108
Gregor Brandt Avatar answered Oct 06 '22 15:10

Gregor Brandt


Here is a function can reverse byte order of any type.

template <typename T> T bswap(T val) {     T retVal;     char *pVal = (char*) &val;     char *pRetVal = (char*)&retVal;     int size = sizeof(T);     for(int i=0; i<size; i++) {         pRetVal[size-1-i] = pVal[i];     }      return retVal; } 
like image 38
Benjamin Avatar answered Oct 06 '22 15:10

Benjamin