如何在C ++中将float转换为vector <unsigned char =“”>?

时间:2018-10-10 13:09:16

标签: c++ vector

我读了Convert float vector to byte vector and back,但这并没有帮助我解决问题。 我想将std::vector<unsigned char>转换回floatunsigned 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;
}

2 个答案:

答案 0 :(得分:2)

要将floatstd::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;
}

答案 1 :(得分:1)

只需将其复制回浮点数即可:

float value;
std::copy( readRequestArray.begin(), readRequestArray.end(), reinterpret_cast<const unsigned char*>( &value ) );

通常,这是通过实现从std::vector<byte>到各种类型的编组功能来完成的,例如:

 template<typename T>
 T read( std::vector<byte>::iterator &it )
 {
     auto prev = it;
     it += sizeof(T);
     T value;
     std::copy( prev, it, reinterpret_cast<byte *>( &value ) );
     return value;
 }

然后使用:

 std::vector<byte> data;
 auto it = data.begin();
 auto floatValue = read<float>( it );
 auto intValue   = read<int>( it );

,但是您需要小心,并且仅将其用于POD类型(也许添加std::enable_if来实施它)。另外,您还需要确保vector具有足够的数据,或者将第二个迭代器传递给函数以验证是否有足够的数据。