将浮点矢量转换为字节矢量并返回

roc*_*ter 4 c++ floating-point byte

我试图在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]);
Run Code Online (Sandbox Code Playgroud)

我希望我已经正确地做到了这一点,如果不是那就是为什么下一部分不会工作的原因.

// 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
Run Code Online (Sandbox Code Playgroud)

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

for (int i = 0; i < 3; i++)
    cout << (float)bytes[i] << endl;
Run Code Online (Sandbox Code Playgroud)

不知道如何从中获取原始浮点值.

谢谢你的帮助.

roc*_*ter 5

解决了:

我认为问题出在这里

vector<unsigned char> byteVec;

for (int i = 0; i < 3; i++)
    byteVec.push_back(bytes[i]);
Run Code Online (Sandbox Code Playgroud)

我删除了它并替换为

vector<unsigned char> byteVec(bytes, bytes + sizeof(float) * myFloats.size());
Run Code Online (Sandbox Code Playgroud)

那么其余的工作正常!

另外,请记住在这里使用(字节)而不是(*bytes)

float* floatArray = reinterpret_cast<float*>(bytes);
Run Code Online (Sandbox Code Playgroud)