[英]Convert float vector to byte vector and back
我试图在float和unsigned char数组之间做一些转换(在这种情况下是std :: vector),我遇到了一些麻烦。
我已经将浮点数向量转换为无符号字符,就像这样......
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
我尝试在最后一部分使用(字节)而不是(*字节),但是打印错误的值。 这样做也会打印错误的值
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)
float* floatArray = reinterpret_cast<float*>(bytes);
我不得不通过TCP发送原始字节数据。 我使用了一个包含单个unsigned char[4]
数组的结构,并使用memcpy
将浮点值中的字节复制到此数组的开头。 它可能不太理想,但它确实适合我的目的。 显然你可以反过来检索数据。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.