Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert between little-endian and big-endian floats effectively

I have a working software, which currently runs on a little-endian architecture. I would like to make it run in big-endian mode too. I would like to write little-endian data into files, regardless of the endianness of the underlying system.

To achieve this, I decided to use the boost endian library. It can convert integers efficiently. But it cannot handle floats (and doubles).

It states in the documentation, that "Floating point types will be supported in the Boost 1.59.0". But they are still not supported in 1.62.

I can assume, that the floats are valid IEEE 754 floats (or doubles). But their endianness may vary according to the underlying system. As far as I know, using the htonl and ntohl functions on floats is not recommended. How is it possible then? Is there any header-only library, which can handle floats too? I was not able to find any.

I could convert the floats to string, and write that into a file, I would like to avoid that method, for many reasons ( performance, disk-space, ... )

like image 537
Iter Ator Avatar asked Nov 28 '25 21:11

Iter Ator


1 Answers

Here:

float f = 1.2f;
auto it = reinterpret_cast<uint8_t*>(&f);
std::reverse(it, it + sizeof(f)); //f is now in the reversed endianness

No need for anything fancy.

like image 198
David Haim Avatar answered Nov 30 '25 11:11

David Haim



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!