struct one {
int a;
double b; };
vector<one> myvector(3);
I'd want to get the byte (char) data from myvector[0], myvector[1], etc.
I'd want to do :
1.- Save myvector[0] into my_char (a *char variable)
2.- Save the char data into a char buffer.
3.- Save the char data into a stream.
4.- Save the char data to a binary file.
What kind of casting (from the diferent castings) can I use ?
One of them are better, faster ?
I understand "reinterpret_cast<char*> (my_vector[0]);" but I have doubts about the other casts (I have read the cppreference but I dont understand nothing....)
Don't cast vectors, or any other type for that matter. Casting is unsafe, and may result in buggy, and undefined behaving code. Some type-casting is safe. For example:
1 2 3 4 5
short Number( 10 );
static_cast < int > ( Number ); // Safe.
static_cast < long > ( Number ); // Safe.
static_cast < longlong > ( Number ); // Safe.
( char )Number; // Safe.
tonnot wrote:
Save myvector[0] into my_char (a *char variable)
Why do you want to cast a structure into a character? Are you trying to perform serialization?
I'm casting vectors to char buffer because I dont know how to write them as a whole object to a binary file. ( And I suposse that in the future I'm going to have send it over the network)
I'm storing data into a char buffer, to send later to a binary file using one instruction.
By now , it works. I'm almost finishing my method.
Thanks
You could do ((char *)&vector[0])
That's safe if you pass that to a function along with vector.size()*sizeof(T), where T is the type of the elements of vector.
Note that if you're using this to send the vector to an I/O device, such as a file or the network, this will write the structures in a way only your computer and computers like yours can understand. Google endianness for more information.
If this is a problem, you should use a different method.
Thanks helios.
I have spent a lot of time in this work....
I have view a lot of web pages and, yes I know the endianness problem.
Why is so difficult to find a good link talking about it and offering a solution?
Why is so difficult to find a good link talking about it and offering a solution?
Because there's no general solution to the problem. The closest to one is "find a consistent format for integers and use it whenever dealing with serial I/O". For example: