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.
Yes, floating point can be endianess dependent.
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.
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.
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.
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