用于ASIO写入的十六进制字符串到字节
hex string to bytes for ASIO write
我使用以下代码用十六进制表示的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
);
相关文章:
- 如何将包含epoch时间的十六进制字符串转换为time_t
- 如何将一个ostringstream十六进制字符串字符对转换为单个unit8t等价的二进制值
- 如何在C++中将十六进制字符串转换为文本数据
- 定义宏以将前缀 0x 添加到十六进制字符串文本
- 将字符串(可以是十进制字符串或十六进制字符串)转换为整数C++
- 将 std::string( "x3BxDEx7C" ) 转换为可读的十六进制字符串?
- C++ 将十六进制字符串表示形式转换为十六进制字符串表示形式
- 字符数组到十六进制字符串的转换 - 意外输出
- C++十进制到十六进制(字符串下标超出范围)
- C++十六进制字符串转换为十六进制的字符 *
- 如何在C++中将十六进制字符串转换为字节字符串?
- 从十六进制字符串转换为十六进制字符数组
- 以C++格式将十六进制字符串转换为十进制数
- 将无符号字符 * 转换为十六进制字符串
- 在C++中将 HWND 转换为十六进制字符串
- 按位函数 AND、OR 和 XOR 在 C++ 中使用十六进制字符串
- 如何将十六进制字符串转换为 HTML 实体
- 查找十六进制字符串是 utf-8 或 utf-16
- 在 c++ 中使用字符串流将 4 个字符的十六进制字符串转换为有符号的短字符串
- 将 std::十六进制字符串转换为 std::array<T, 6>