gpt4 book ai didi

c++ - 将字节 vector 转换为浮点 vector

转载 作者:行者123 更新时间:2023-11-30 03:17:08 25 4
gpt4 key购买 nike

我正在通过串行端口向另一台计算机发送固定长度的字节流,我想尝试将字节流转换为 float vector 。

我的流有一个分隔符 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)

然后将字符串转换为 vector

   std::vector<unsigned char>bytes(stop_string.begin(), stop_string.end());

然后我使用 for 循环和 memcpybytes 转换为 float 数组。

     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 vector 转换为 float vector ?

  • 避免 for 循环?

最佳答案

float 数组和无符号字符 vector 的字节大小相同。您可以直接从缓冲区 memcpy 到 float 数组中。

这并不是说你的字节被交换了或什么的。您只想将 4 个连续字节解释为 float 。

这也消除了循环 🙂

编辑更新:

如果您使用的是 C++11 或更高版本,您可以相信 std::string's internal buffer is stored contiguously直接从那里复制。不需要临时字节缓冲区,这会为您节省大量内存(半页)。

例子:

// copy directly from string
float float_values[data_string.size()/sizeof(float)]; // 513
std::memcpy(float_values, data_string.data(), data_string.size());

关于c++ - 将字节 vector 转换为浮点 vector ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55755277/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com