[英]convert a byte vector into a vector of floats
我正在通过串行端口将固定长度的字节流发送到另一台计算机,我想尝试将字节流转换为浮点数的向量。
我的流有一个定界符stop
符,我正在使用此串行库。
我当前的实现涉及以下内容:
我读了一个字符串
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循环?
自从您标记为通用C ++以来,我将使用C ++ 20引入的一些很酷的新功能:)
#include <algorithm>
#include <cstddef>
#include <span>
#include <vector>
std::vector<float> ToFloats(const std::vector<std::byte>& bytes) {
std::vector<float> floats(bytes.size() / sizeof(float), 0.0f);
std::copy_n(bytes.begin(), floats.size() * sizeof(float),
std::as_writable_bytes(std::span(floats)).begin());
return floats;
}
浮点数数组和无符号字符向量均以字节为单位。 您可以直接将memcpy存入缓冲区的float数组中。
这好像不是您的字节被交换之类的。 您只想将4个连续字节解释为一个浮点数。
这也消除了循环
编辑更新:
如果您使用的是C ++ 11或更高版本,则可以依靠以下事实: std :: string的内部缓冲区是连续存储的 ,只需直接从中复制即可。 不需要临时字节缓冲区,这样可以为您节省大量内存(半页)。
例:
// copy directly from string
float float_values[data_string.size()/sizeof(float)]; // 513
std::memcpy(float_values, data_string.data(), data_string.size());
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.