c++ - 如何将浮点数转换为向量在 C++ 中?
问题描述
我阅读了将浮点向量转换为字节向量并返回,但它并没有帮助我解决我的问题。我想转换std::vector<unsigned char>
回float
. 上的行unsigned char* bytes = &(readRequestArray);
不起作用,上面的行我只打印字节。如何转换回浮点数?
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;
}
解决方案
要将 a 转换为 afloat
和从 a转换,std::vector<unsigned char>
您可以使用以下命令
auto to_vector(float f)
{
// get vector of the right size
std::vector<unsigned char> data(sizeof(f));
// copy the bytes
std::memcpy(data.data(), &f, sizeof(f));
return data;
}
auto from_vector(const std::vector<unsigned char>& data)
{
float f;
// make sure the vector is the right size
if (data.size() != sizeof(f))
throw std::runtime_error{"Size of data in vector and float do not match"};
// copy the bytes into the float
std::memcpy(&f, data.data(), sizeof(f));
return f;
}
int main()
{
float foo = 3.14;
auto data = to_vector(foo);
auto ret = from_vector(data);
std::cout << ret;
}