gpt4 book ai didi

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

转载 作者:塔克拉玛干 更新时间:2023-11-03 01:30:45 31 4
gpt4 key购买 nike

我正在尝试在 float 和 unsigned char 数组(在本例中为 std::vector)之间进行一些转换,但遇到了一些麻烦。

我已经像这样将 float vector 转换为 unsigned char...

vector<float> myFloats;
myFloats.push_back(1.0f);
myFloats.push_back(2.0f);
myFloats.push_back(3.0f);

const unsigned char* bytes = reinterpret_cast<const unsigned char*>(&floats[0]);

vector<unsigned char> byteVec;

for (int i = 0; i < 3; i++)
byteVec.push_back(bytes[i]);

我希望我做对了,否则这就是下一部分无法工作的原因。

// converting back somewhere later in the program
unsigned char* bytes = &(byteVec[0]); // point to beginning of memory
float* floatArray = reinterpret_cast<float*>(*bytes);

for (int i = 0; i < 3; i++)
cout << floatArray[i] << endl; // error here

我尝试在最后一部分使用 (bytes) 而不是 (*bytes),但打印出错误的值。这样做也会打印出错误的值

for (int i = 0; i < 3; i++)
cout << (float)bytes[i] << endl;

不确定如何从中取回我原来的浮点值。

感谢您的帮助。

最佳答案

已解决:

我认为问题出在这里

vector<unsigned char> byteVec;

for (int i = 0; i < 3; i++)
byteVec.push_back(bytes[i]);

我删除了它并将其替换为

vector<unsigned char> byteVec(bytes, bytes + sizeof(float) * myFloats.size());

然后剩下的工作正常!

另外,记得在这里使用 (bytes) 而不是 (*bytes)

float* floatArray = reinterpret_cast<float*>(bytes);

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

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