I read Convert float vector to byte vector and back but it didn't help me to solve my issue.
I want to convert std::vector<unsigned char>
back to a float
. The line on unsigned char* bytes = &(readRequestArray);
is not working and the lines above I am only printing bytes. How do I convert back to a float?
class HCSR04: public ISensor {
public:
HCSR04();
HCSR04(int trigger, int echo);
~HCSR04();
float distanceCentimeters();
std::vector<unsigned char> readRequest();
}
std::vector<unsigned char> HCSR04::readRequest() {
float preCent = distanceCentimeters();
const unsigned char* bytes = reinterpret_cast<const unsigned char*>(&preCent);
std::vector<unsigned char> buffer(bytes, bytes + sizeof(float));
for (int j = 0; j < buffer.size(); j++) {
std::cout << buffer[j];
}
std::cout << std::endl;
return buffer;
}
int main(void) {
std::vector<unsigned char> readRequestArray = sensorUltrasonic->readRequest();
for (int j = 0; j < readRequestArray.size(); j++) {
std::cout << readRequestArray[j];
}
std::cout << std::endl;
unsigned char* bytes = &(readRequestArray);
for (int i = 0; i < 3; i++)
std::cout << (float) bytes[i] << std::endl;
}