简体   繁体   中英

C++ How to convert a vector<uint8_t> of size 4 into a 32 bit float

What is the fastest way to convert a vector of size 4 into a 32 bit float?

My failed attempt:

static bool vec2float32(std::vector<uint8_t> bytes, float &result)
{
    if(bytes.size() != 4) return false;
    uint8_t sign = (bytes.at(0) & 0x10000000); //will be 1 or 0
    uint8_t exponent = (bytes.at(0) & 0x01111111);
    uint16_t mantissa = (bytes.at(1) << (2*8)) + (bytes.at(2) << (1*8)) + (bytes.at(3) << (0*8));

    result = (2^(exponent - 127)) * mantissa;
    if(sign == 1) result = result * -1;
    return true;
}

I believe this should be the fastest:

return *reinterpret_cast<float*>(&bytes[0]);

I think its technically undefined behavior. But most compilers should output what you expect here. The &bytes[0] is guaranteed to work because std::vector is guaranteed to be contiguous.

From the vector you can get a pointer to the first byte. If the bytes are already in the correct order, then you can copy the bytes directly into a float variable.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM