Gyiove wrote: |
---|
both float and int are 4 bytes |
No, not necessarily. This isn't true in a significant number of cases. Also, the C-style cast will do a type conversion, not reinterpretation. Use
reinterpret_cast
on the address of your float instead.
What kind of machine has the float's byte order different? |
AMD and Intel processors are big and little-endian, respectively. Other architectures, (for example, ARM v3+), support both byte orders. Rarely, the floating-point byte order doesn't match the processors' endianness. You can't assume one or the other. Convert to network byte order before sending it.
zoran404 wrote: |
---|
How do you serialize floats when writing it to a file or sending it via socket? |
Write it out as text. That's foolproof.
If you must write it out in a binary format, then you can store it however you want, as long as you don't assume anyone else can read it back. For local data files, you can just write out the bytes in host order, or if you care about being able to share it, convert it to network byte order.
If you're reading/writing it from/to a socket, convert it (if you need to) using
hton[ls]()
and
ntoh[ls]()
.