简体   繁体   中英

Convert double to char array without padding in c++

I am trying to send a double through a UDP winsock using the Sendto function but first I need to convert it to a char[]. After trying multiple approaches, the best thing I came up with is the following:

    // send 
    memset(buf, '\0', BUFLEN);
    double a = position.y();
    char arr[sizeof(a)];
    cout << "double" << a << endl;
    ToString(arr, sizeof(a), a);

    sendto(s, arr, strlen(arr), 0, (struct sockaddr *) &si_other, slen);
    cout << "Send" << arr << endl;

This unfortunately gives out a weird trailing padding that ruins the send operation. Any ideas on how to solve this?

My ToString function is the following:

void ToString(char * outStr, int length, double val)
{
     _snprintf(outStr, length, "%f", val);
}

The output looks like this:

double 0.003
Send 0.003(a bunch of gibberish)

You are assuming that the number of bytes that the binary double occupies is the same length as the converted string occupies but that is unlikely.

If you have C++11 you can do something like this:

void send_double(int s, sockaddr* si_other, int slen, double d)
{
    auto buf = std::to_string(d);
    sendto(s, buf.data(), buf.size(), 0, si_other, slen);
}

Otherwise you can do something like this:

void send_double(int s, sockaddr* si_other, int slen, double d)
{
    std::ostringstream oss;
    oss << d;
    std::string buf = oss.str();
    sendto(s, buf.data(), buf.size(), 0, si_other, slen);
}

See std::string , std::to_string and std::ostringstream

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM