user1095108
user1095108

Reputation: 14603

swapping "endianness" of floats and doubles

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.

Upvotes: 5

Views: 2507

Answers (2)

Joshua Bonner
Joshua Bonner

Reputation: 21

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.

Upvotes: 1

1stCLord
1stCLord

Reputation: 880

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.

Upvotes: 3

Related Questions