-2

I need to send a series of floats over a TCP socket.

Firstly, is it safe to assume that most platforms (e.g off the shelf Windows PC/Laptop) and architectures represent floats in the same way (i.e IEEE 754)?

If so, I was thinking of doing something like this:

float a = 29.054;
int* b = reinterpret_cast<int*>(&a);

//Store in byte array

Would this work?

  • I think you may run into undefined behavior due to strict aliasing with this code if you are compiling with GCC. My solution for this in the past was to make a custom int typedef that had the __may_alias__ attribute that explicitly allowed type punning (then I'd use that instead of int). MSVC does not have any strict aliasing optimizations. – jrh Jun 25 at 12:40
3

It's probably safe to assume that most platforms support IEEE floats. That implies that you don't care about the other platforms. It will be mainly embedded systems that won't have an IEEE-compliant floating point maths processor.

Floats can suffer from endianness problems just like integers. Make sure that you define what endianness you are using (big endian or little endian), and ensure that the numbers are byte swapped on platforms that need it.

| improve this answer | |
  • Thanks. Regarding the second part of the question, do you think using a reinterpret_cast is the right way to go? I assume I can also cast to a char buffer, instead of an int? – 19172281 Jun 25 at 13:55
  • And out of interest, are most platforms moving towards IEEE floats? – 19172281 Jun 25 at 13:56
  • @19172281 reinterpret_cast is not enough, you have to manually swap bytes before reinterpreting if the network byte order doesn't match your system's. Though to be fair Big Endian CPUs are not very common these days in desktop / laptop computers; PowerPC was the last mainstream Big Endian system I remember offhand – jrh Jun 25 at 14:08
  • Assuming the byte order is correct and doesn't need swapping, is the reinterpret_cast appropriate? – 19172281 Jun 25 at 14:10
  • Also, how would you swap the byte order before casting? Why couldn't you swap after the cast? – 19172281 Jun 25 at 14:11
3

You can check std::numeric_limits<float>::is_iec559 and fail to compile for platforms that use other representation

| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.