【问题标题】:How can I convert boost::asio::streambuf to float?如何将 boost::asio::streambuf 转换为浮点数?
【发布时间】:2016-01-29 02:54:34
【问题描述】:

我正在从串行端口读取数据。我设法设置了端口,并且可以读入缓冲区,但我不知道如何将缓冲区保存的数据转换为浮点数。

float Serial::ReadData()
{
    boost::asio::streambuf buff;
    int bytesRead = read_until(*port, buff, "\n");
    boost::asio::const_buffers_1 constBuff = buff.data();
    char*data = nullptr;
    int pos = 0;
    for (auto buffer = constBuff.begin(); buffer != constBuff.end(); buffer++)
    {
        data[pos] = reinterpret_cast<char>(buffer);
        pos++;
    }
    buff.consume(bytesRead);
    return atof(data);
}

【问题讨论】:

  • 您甚至没有指定 streambuf 包含的内容。是二进制的吗? ASCII?基数64?压缩? IEEE 原始字节?'
  • 我正在从连接到 com 端口的蓝牙读取数据,所以我相信它正在发送原始字节。
  • 在这种情况下,您的自我回答完全没有意义。 en.cppreference.com/w/cpp/string/byte/atof 更重要的是,除非你知道确切的电汇格式,否则没有人能真正回答。请注意,我的回答在逻辑上与您的atof 相同。我要冒昧地提出建议 - 显然 - 你已经发现格式是文本表示。
  • 这种情况下一定是Ascii。

标签: c++ boost serial-port


【解决方案1】:

或者

Live On Coliru

现在它看起来实际上是等价的,但是:

  • 不会泄露内存
  • 它不会不必要地复制缓冲区
  • 它处理错误
  • 如果您想解析不止 1 个东西,它会更加灵活
#include <boost/asio.hpp>
#include <iostream>
#include <stdexcept>

struct Serial {
    float ReadData();

    boost::asio::serial_port* port = nullptr;
};

float Serial::ReadData()
{
    boost::asio::streambuf buff;
    /*int bytesRead = */read_until(*port, buff, "\n");
    std::istream is(&buff);
    float f;
    if (is >> f)
        return f;
    throw std::invalid_argument("ReadData");
}

int main(){}

【讨论】:

    【解决方案2】:

    嗯,我想出了怎么做。它比我最初想象的要简单得多。

    float Serial::ReadData()
    {
        boost::asio::streambuf buff;
        int bytesRead = read_until(*port, buff, "\n");
        char*data = new char[bytesRead];
        buff.sgetn(data, bytesRead);
        return atof(data);
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-08-06
      • 1970-01-01
      • 2017-09-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-09-19
      • 1970-01-01
      相关资源
      最近更新 更多