【发布时间】:2019-09-09 08:05:21
【问题描述】:
我正在通过串行端口向另一台计算机发送一个固定长度的字节流,我想尝试将字节流转换为浮点数向量。
我的流有一个分隔符stop,我正在使用this 串行库。
我目前的实现涉及以下内容:
我读了一个字符串
std::string data_string;
ser.readline(data_string, 2052, "stop");
检查字符串是否以分隔符结尾
if(boost::algorithm::ends_with(stop_string, "stop"))
{
if(data_string.length() == 2052)
然后将字符串转换为向量
std::vector<unsigned char>bytes(stop_string.begin(), stop_string.end());
然后我使用 for 循环和 memcpy 将 bytes 转换为浮点数数组。
unsigned char temp_buffer[4];
float float_values[513] = { 0 };
int j = 0;
for(size_t i = 4; i < 2052; i+=4)
{
temp_buffer[0] = bytes[i - 4];
temp_buffer[1] = bytes[i - 3];
temp_buffer[2] = bytes[i - 2];
temp_buffer[3] = bytes[i - 1];
memcpy(&float_values[j], temp_buffer, sizeof(float));
j++;
}
但是这种方法看起来很麻烦,我想避免 for 循环。有没有办法:
将
bytes向量转换为浮点数向量?避免 for 循环?
【问题讨论】:
-
如果您觉得这个答案有用,请考虑“接受”它(通过单击旁边的勾号 (✓))以表明您已经找到了一个可行的解决方案,也让其他人可以更轻松地以后再找。