Is it possible to convert float
s 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_ulong
on that value, I always get 0.0000?
What am I doing wrong?
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.
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.
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.
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).
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; }
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; }
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