1

I have some code which I need to serialize a vector into bytes, then send it to a server. Later on, the the server replies with bytes and I need to serialize it back into a vector.

I have managed to serialize into bytes okay, but converting back into a vector is getting the wrong values:

#include <iostream>
#include <string>
#include <vector>


int main()
{
    std::vector<double> v = {1, 2, 3};
    std::cout << "Original vector: " << std::endl;
    for (auto i : v) {
        std::cout << i << " ";
    }
    std::cout << std::endl;

    std::string str((char *)v.data(), sizeof(v[0])*v.size());
    std::cout << "Vector memory as string: " << std::endl << str << std::endl;

    std::cout << "Convert the string back to vector: " << std::endl;
    auto rV = std::vector<double>(&str[0], &str[str.size()]);
    for (auto i : rV){
        std::cout << i << " ";
    }
    std::cout << std::endl;

    return 0;
}

This outputs:

Original vector: 
1 2 3 
Vector memory as string: 
�?@@
Convert the string back to vector: 
0 0 0 0 0 0 -16 63 0 0 0 0 0 0 0 64 0 0 0 0 0 0 8 64 

What is going wrong with my conversion from a string to a vector, and how can I fix it?

Here is a link to run the code.

15
  • 1
    So, you want each element of the vector to be altogether displayed like 1 2 3 as a string? Commented Dec 1, 2022 at 12:05
  • @RohanBari Thats correct Commented Dec 1, 2022 at 12:05
  • 2
    I would recommend using some serialization library. IIRC, Boost.Serialization can work with vectors. Commented Dec 1, 2022 at 12:20
  • 1
    @TomMcLean there are platforms where doubles must start on addresses that are multiples of 8, the CPU can't load them otherwise Commented Dec 1, 2022 at 13:39
  • 1
    Since you control both ends (both the client and server), you just need to be mindful. Since what you have works, it works. Which is okay, because good enough is good enough. Commented Dec 1, 2022 at 13:49

1 Answer 1

4

Like this

std::vector<double>((double*)str.data(), (double*)(str.data() + str.size()));

Basically the same as your code, but I've added some casts. In your version the chars get converted directly into doubles (as if you had written rV[0] = str[0] etc) and the vector is sizeof(double) times too big.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.