Convert float vector to byte vector and back

前端 未结 2 1039
情歌与酒
情歌与酒 2021-01-13 12:58

I\'m trying to do some conversions between float and unsigned char arrays (std::vector in this case) and i\'ve run into some troubles.

I\'ve converted the vector of

相关标签:
2条回答
  • 2021-01-13 13:41

    Solved:

    I think the problem was here

    vector<unsigned char> byteVec;
    
    for (int i = 0; i < 3; i++)
        byteVec.push_back(bytes[i]);
    

    I removed that and replaced it with

    vector<unsigned char> byteVec(bytes, bytes + sizeof(float) * myFloats.size());
    

    then the rest works fine!

    Also, remember to use (bytes) instead of (*bytes) here

    float* floatArray = reinterpret_cast<float*>(bytes);
    
    0 讨论(0)
  • 2021-01-13 13:54

    I have had to do this kind of thing for sending raw byte data over TCP. I used a struct that contains a single unsigned char[4] array and use memcpy to copy the bytes in my float values to the start of this array. It may not be ideal but it does work well enough for my purposes. Obviously you can do the reverse to retrieve the data.

    0 讨论(0)
提交回复
热议问题