Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

swapping "endianness" of floats and doubles

Tags:

I'd like to switch the "endianness" of float and double values, it works OK, by doing something like:

float const v{1.f};

swap(reinterpret_cast<::std::uint32_t const&>(v));

Does there exist a better way to do the swap, without a cast?

EDIT: swap() is a C++ wrapper for gcc's built-in functions, I did not include it here.

uint16_t __builtin_bswap16 (uint16_t x)
uint32_t __builtin_bswap32 (uint32_t x)
uint64_t __builtin_bswap64 (uint64_t x)

Swapping of endianess is needed for a some data formats, like CBOR.

like image 964
user1095108 Avatar asked Aug 09 '16 20:08

user1095108


People also ask

Does float have Endianness?

Yes, floating point can be endianess dependent.

Are floats more efficient than doubles?

Float and doubleDouble is more precise than float and can store 64 bits, double of the number of bits float can store. Double is more precise and for storing large numbers, we prefer double over float.


2 Answers

While it is good practice to try and avoid casts, it's uses like this that are the reason casts exist. An endian swap is a raw data operation so in order to do it you must strip away the typing information, I would say that if it is not endian correct to begin with, then it is not a float and should never have been typed that way while in the wrong endianess state.

like image 91
1stCLord Avatar answered Sep 23 '22 16:09

1stCLord


Simply swapping the byte order is sufficient. memcpy the float into a char val[4], create a dummy char rvrse[4], then set; rvrse[3] = val[0]; rvrse[2] = val[1]; ... Then memcpy rvrse back into the original float. The best way is to write a function similar to ntohl but use templates to make it work for all types.

like image 25
Joshua Bonner Avatar answered Sep 24 '22 16:09

Joshua Bonner