If you want to convert in text mode, you have multiple options. The most typical of C ++ is to use the stream of strings, or stringstream . The idea is to enter data in a stream , just as you would do with, for example, cout , and get a text string. For this, we will need a stringstream output, that is, a ostringstream . These classes are in the sstream header.
ostringstream cnvt;
cnvt << 32.121;
cout << cnvt.str() << endl;
If you want to do the binary conversion, you can do it in two ways, both "old-fashioned":
Copy the contents of the memory from one to another :
char bytes[sizeof(double)];
double x = 32.121;
// Copying memory
memcpy( bytes, &x, sizeof(x) );
for(int i = 0; i < sizeof( x ); ++i) {
cout << bytes[ i ] << ' ';
}
When copying from the start of x ( &x
), the number of bytes occupied by x ( sizeof(x)
), you ensure you are copying the content whole of the variable. The target array must be the same size, of course.
Use a union
The union is hardly used today, although for this case they fit like a glove. All the members of a union start at the same memory address, so by modifying one of them, you are modifying them all at once.
union Conversor {
char bytes[sizeof( double )];
double x;
};
Thus, the modify Converter . x , we obtain the value conveniently decomposed in Converter . bytes .
Conversor cnvt;
cnvt.x = 32.121;;
for(int i = 0; i < sizeof( x ); ++i) {
cout << cnvt.bytes[ i ] << ' ';
}
You have the full IDEOne code .