C++ 将浮点向量转换为字节向量并返回
我试图在浮点和无符号字符数组(本例中为std::vector)之间进行一些转换,但遇到了一些问题 我已将浮点向量转换为无符号字符,如下所示C++ 将浮点向量转换为字节向量并返回,c++,floating-point,byte,C++,Floating Point,Byte,我试图在浮点和无符号字符数组(本例中为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*&g
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]);
向量myfloat;
myFloats.向后推(1.0f);
myFloats.向后推(2.0f);
myFloats.向后推(3.0f);
const unsigned char*bytes=reinterpret_cast(&floats[0]);
向量字节向量;
对于(int i=0;i<3;i++)
字节向量推回(字节[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
//稍后将转换回程序中的某个位置
无符号字符*字节=&(字节向量[0]);//指向记忆的开始
float*floatArray=reinterpret_cast(*字节);
对于(int i=0;i<3;i++)
cout我不得不通过TCP发送原始字节数据。我使用了一个包含单个无符号字符[4]
数组的结构,并使用memcpy
将浮点值中的字节复制到此数组的开头。它可能不太理想,但对我的目的来说,它确实工作得很好。显然,您可以执行相反的操作来检索数据。已解决:
我想问题就在这里
vector<unsigned char> byteVec;
for (int i = 0; i < 3; i++)
byteVec.push_back(bytes[i]);
向量字节向量;
对于(int i=0;i<3;i++)
字节向量推回(字节[i]);
我把它取下来,换成了
vector<unsigned char> byteVec(bytes, bytes + sizeof(float) * myFloats.size());
向量字节向量(字节,字节+sizeof(float)*myFloats.size());
那么剩下的就好了
此外,请记住在此处使用(字节)而不是(*字节)
float*floatArray=reinterpret\u cast(字节);
重新解释强制转换(字节)代码>(请注意,parens中没有星星)。我在我的帖子中说,我已经尝试过了。我使用(字节)打印的第一个值是-2.1267e+037。也许是常量?我可以用memcpy来表示一个大的字节数组到一个大的浮点数组吗?不确定一次做一个是否有效。确切地说,你应该使用sizeof(float)
而不是硬编码数字4。是的,你是对的。事实上,我创建了无符号字符数组来存储混合数据类型——我只是用4来说明一般的想法。
vector<unsigned char> byteVec(bytes, bytes + sizeof(float) * myFloats.size());
float* floatArray = reinterpret_cast<float*>(bytes);