Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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;
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
276 views
Welcome To Ask or Share your Answers For Others

1 Answer

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...