I’m sure this is a very common operation when doing any kind of network programming (or I/O with files) but I can’t find the answer.
Basically I have a datagram packet coming in down the network which has a series of single precision floating point numbers (4 bytes each).
I have written some basic networking code which reads from a socket and stores the data into a buffer which is declared as follows:
char buffer[24];
This is my deserialization code:
for (int i=0; i<6; i++) {
float *pf = reinterpret_cast<float*>(buffer + i*sizeof(float));
printf("%f\n", *pf);
}
but it causes my program to crash.
If someone could point me to a good tutorial on this type of thing i.e. managing, storing and interpreting data, I’d really appreciate it! I’ve looked but I don’t know what to search for.
If they are really sending floats — which I wouldn’t recommend, if you have a choice — then you have to do some bit hackery.
Here is a utility library I wrote to do just this kind of thing. It works on Windows (MSVC) and Linux (GCC). It might not work on other platforms! Use at your own risk.