简体   繁体   English

将双精度转换为char数组而无需在C ++中进行填充

[英]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[]. 我正在尝试使用Sendto函数通过UDP winsock发送一个double,但是首先我需要将其转换为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: 我的ToString函数如下:

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. 您假设二进制double精度占用的字节数与转换后的字符串占用的字节数相同,但这不太可能。

If you have C++11 you can do something like this: 如果您拥有C++11 ,则可以执行以下操作:

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 参见std :: stringstd :: to_stringstd :: ostringstream

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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