如何将浮点数转换为向量<无符号字符>在 C++ 中? [英] How to convert float to vector&lt;unsigned char&gt; in C++?

查看:43
本文介绍了如何将浮点数转换为向量<无符号字符>在 C++ 中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我阅读了将浮点向量转换为字节向量并返回 但这并没有帮助我解决我的问题.我想将 std::vector 转换回 float.unsigned char* bytes = &(readRequestArray); 上的行不起作用,上面的行我只打印字节.如何转换回浮点数?

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;
}

推荐答案

要将 float 转换为 std::vector,您可以使用以下

To convert a float to and from a std::vector<unsigned char> you can use the following

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;
}

这篇关于如何将浮点数转换为向量<无符号字符>在 C++ 中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆