简体   繁体   English

C ++如何转换向量 <uint8_t> 大小4变成32位浮点数

[英]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? 将大小为4的向量转换为32位浮点数的最快方法是什么?

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. 保证&bytes [0]可以工作,因为保证std :: vector是连续的。

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. 如果字节已经按照正确的顺序排列,则可以将字节直接复制到float变量中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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