Hello there, I'm having some trouble trying to converting images/characters/strings/data into a byte array and then send them.

In C++, I already have established a connection between the client - server and would like to send and receive data.

Now I'd like to send an install file which is like 1.3MB. How do I convert that into a byte array and then send it to the other side and convert it into the original file?

If possible, can you include a detailed example? It's hard as it is to just understand the concept.

Cheers!

Ignoring details such as packing, endianness, and pointer issues the most basic approach is something similar to the following

template <typename T>
inline void pack (std::vector< uint8_t >& dst, T& data) {
    uint8_t * src = static_cast < uint8_t* >(static_cast < void * >(&data));
    dst.insert (dst.end (), src, src + sizeof (T));
}   

template <typename T>
inline void unpack (vector <uint8_t >& src, int index, T& data) {
    copy (&src[index], &src[index + sizeof (T)], &data);
}

And you can use that like

// on the send side
vector< uint8_t > buffer;
uint32_t foo = 103, bar = 443;
pack (buff, foo);
pack (buff, bar);

// And on the receive side
uint32_t a = 0, b = 0;
size_t offset = 0;
unpack (buffer, offset, a);
offset += sizeof (a);
unpack (buffer, offset, b);
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.