'Why is there no available byte order conversion method for floating-point numbers? Also, why do floating-point numbers work without conversion?
I am working on parsing packets received in binary format. I have to do byte order conversion for integrals, but it is a bit strange for me as it seems floating-point numbers work fine without conversion. Are floating-point numbers are always in little-endian byte order? Why don't we have ntof or ntod function in arpa/inet or other Unix network libraries?
Solution 1:[1]
Why is there no available byte order conversion method for floating-point numbers?
The representation with flipped byte order can't be placed into a floating-point variable at all, due to signalling NaNs.
To do byte order conversion for floating-point values, read from the input into an integer-typed or untyped (e.g. array of std::byte) buffer, use a byte swap operation that works on such a buffer, and reinterpret as a floating-point value only after the byte order is corrected.
For output, reinterpret into a buffer first, and then do the byte order swap on the buffer (which has no floating-point type).
Are floating-point numbers are always in little-endian byte order?
No.
Why don't we have
ntohforntohdfunction in arpa/inet or other Unix network libraries?
None of the packets in any standard protocol contain floating-point numbers. The network library isn't providing ntohs and ntohl for convenient manipulation of application data, but for manipulation of header fields such as IP address and TCP port number.
If you do define convenience functions for yourself, be sure to use a non-floating-point type for the network side. That is, you should write
uint32_t htonf(float);
float ntohf(uint32_t);
uint64_t htond(double);
double ntohd(uint64_t);
or probably even better, break with the scalar-in-scalar-out convention and use std::span<std::byte, width> for the network-side. This will resolve the alignment issues that would otherwise arise with stuffing the IEEE double-precision bit representation into a uint64_t, since the standard network protocols only provide 32-bit alignment.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
