我试图在float和unsigned char数组之间进行一些转换(在本例中为std :: 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
我试过使用(字节)而不是(*字节)在最后一部分,但打印错误的值。这样做也打印了错误的值
for (int i = 0; i < 3; i++)
cout << (float)bytes[i] << endl;
不知道如何让我的原始浮动值返回此。
感谢您的任何帮助。
'的reinterpret_cast(字节);'(注意如何还有的括号内无星级)。 –
我在帖子中说过我已经试过了。我打印出来的第一个值(字节)是-2.1267e + 037。也许它的常量? – rocklobster