Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ floats and doubles on different platforms/architectures

For context, I'm developing a library for Arduino to transfer data packets over LoRa receivers.

Question I'm having is, the library is placing the raw bits from floats and doubles into uint8_t arrays, sending them and then tranferring them back into floats and doubles.

This of course works when the compiler, platform and architecture is the same, but will I run into problems when unpacking them and simply copying the data straight to a float on other platforms like C++ on Windows or Linux?

I could of course use integers and have some factor to retain decimal places but this adds complexity I'd rather somehow work around.

like image 502
Chris Steffen Avatar asked Jan 27 '26 19:01

Chris Steffen


1 Answers

If your implementation uses ieee754 floating point numbers, and also has unsigned 32 and 64 bit integers, then most likely there is a one-to-one correspondence between float and 32 bit integers, and between double and 64 bit integers. And that applies to exactly 100% of implementations that I’ve used in the last ten years. (Long double is more variable).

So you can move a float into a 32 bit unsigned int, store the four bytes in some fixed order by storing x>>24, x>>16, x>>8 and x as bytes in any fixed order, and read them back in the same order. Same for double with 64 bit.

Alternatively, you store the numbers as text as JSON does.

like image 178
gnasher729 Avatar answered Jan 29 '26 09:01

gnasher729