Converter vetor de flutuação em vetor de byte e voltar
Eu estou tentando fazer algumas conversões entre float e unsigned char arrays (std :: vector, neste caso) e eu corri em alguns problemas.
Eu converti o vetor de floats para unsigned char assim ...
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]);
Eu estou esperando que eu tenha feito isso corretamente, se não for essa a razão pela qual a próxima parte não vai funcionar.
// 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
Eu tentei usar (bytes) em vez de (* bytes) nessa última parte, mas isso imprime os valores errados. Isso também imprimiu os valores incorretos
for (int i = 0; i < 3; i++)
cout << (float)bytes[i] << endl;
Não sei como recuperar meus valores originais de float.
Obrigado por qualquer ajuda.