jeudi 2 mars 2017

How to store bytes of a float value in a string and retrieve the value afterwards?

I'm trying to figure out a way to send a sequence of float values over the network. I've seen various answers for this, and this is my current attempt:

#include <iostream>
#include <cstring>

union floatBytes
{
    float value;
    char bytes[sizeof (float)];
};

int main()
{
    floatBytes data1;
    data1.value = 3.1;
    std::string string(data1.bytes);
    floatBytes data2;
    strncpy(data2.bytes, string.c_str(), sizeof (float));

    std::cout << data2.value << std::endl; // <-- prints "3.1"

    return 0;
}

Which works nicely (though I suspect I might run into problems when sending this string to other systems, please comment).

However, if the float value is a round number (like 3.0 instead of 3.1) then this doesn't work.

data1.value = 3;
std::string string(data1.bytes);
floatBytes data2;
strncpy(data2.bytes, string.c_str(), sizeof (float));

std::cout << data2.value << std::endl; // <-- prints "0"

So what is the preferred way of storing the bytes of a float value, send it, and parse it "back" to a float value?

Aucun commentaire:

Enregistrer un commentaire