用于ASIO写入的十六进制字符串到字节

hex string to bytes for ASIO write

本文关键字:十六进制 字符串 到字节 ASIO 用于      更新时间:2023-10-16

我使用以下代码用十六进制表示的data = "x35x0d"(即5和回车)写入串行设备:

    boost::asio::write(
        *serial_port,
        boost::asio::buffer(data.c_str(), data.size()), 
        boost::asio::transfer_at_least(data.size()),
        error
    );

如何将字符串"350d"转换为字节字符串以用于写入串行端口?并不是我所有的命令都是硬编码的。非常感谢。

这是我不久前为一个简单的工具编写的一些代码。其中包含两个方向的转换。这不是唯一的方式,而是一种方式。

// Convert binary data to hex string
std::string to_hex( const std::vector<uint8_t> & data )
{
  std::ostringstream oss;
  oss << std::hex << std::setfill('0');
  for( uint8_t val : data )
  {
    oss << std::setw(2) << (unsigned int)val;
  }
  return oss.str();
}
// Convert hex string to binary data
std::vector<uint8_t> from_hex( const std::string & s )
{
  std::vector<uint8_t> data;
  data.reserve( s.size() / 2 );
  std::istringstream iss( s );
  iss >> std::hex;
  char block[3] = {0};
  while( iss.read( block, 2 ) )
  {
    uint8_t val = std::strtol( block, NULL, 16 );
    data.push_back( val );
  }
  return data;
}

您需要各种标题:<cstdint><iomanip><sstream><string><vector>

此函数适用于我:

std::string hex_str_to_binary(std::string hex_str) 
{
    std::string binary_str, extract_str;
    try
    {
        assert(hex_str.length() % 2 == 0);  // throw exception if string length is not even
        binary_str.reserve(hex_str.length()/2);
        for (std::string::const_iterator pos = hex_str.begin(); pos < hex_str.end(); pos += 2)
        {
            extract_str.assign(pos, pos + 2);
            binary_str.push_back(std::stoi(extract_str, nullptr, 16));
        }
    }
    catch (const std::exception &e)
    {
        std::cerr << "e.what() = " << e.what();
        throw -1;
    }
    return binary_str;
}

hex_str将看起来像"350d"。我使用小写字母,并确保您的字符串长度均匀,并用0填充空格。然后使用这个字符串进行asio写入:

    boost::asio::write(
        *serial_port,
        boost::asio::buffer(binary_str.c_str(), binary_str.size()), 
        boost::asio::transfer_at_least(binary_str.size()),
        error
    );