How to convert float to byte array of length 4 (array of char*) ? I need to send over network some data, tcp, and need to send float as a byte array. ( I know precision to two d
Reading any type as a sequence of bytes is quite simple:
float f = 0.5f;
unsigned char const * p = reinterpret_cast(&f);
for (std::size_t i = 0; i != sizeof(float); ++i)
{
std::printf("The byte #%zu is 0x%02X\n", i, p[i]);
}
Writing to a float from a network stream works similarly, only you'd leave out the const
.
It is always permitted to reinterpret any object as a sequence of bytes (any char
-type is permissible), and this expressly not an aliasing violation. Note that the binary representation of any type is of course platform dependent, so you should only use this for serialization if the recipient has the same platform.