fork download
  1. #include <iostream>
  2. #include <cstring>
  3. #include <sstream>
  4. using namespace std;
  5.  
  6. union Conversor {
  7. char bytes[sizeof( double )];
  8. double x;
  9. };
  10.  
  11. int main()
  12. {
  13. char bytes[sizeof(double)];
  14. double x = 32.121;
  15.  
  16. cout << "Sizeof char: " << sizeof( char ) << endl;
  17. cout << "Sizeof double: " << sizeof( double ) << endl;
  18.  
  19. // Copying memory
  20. memcpy( bytes, &x, sizeof(x) );
  21.  
  22. for(int i = 0; i < sizeof( x ); ++i) {
  23. cout << bytes[ i ] << ' ';
  24. }
  25.  
  26. // Using a union
  27. Conversor cnvt;
  28. cnvt.x = x;
  29.  
  30. for(int i = 0; i < sizeof( x ); ++i) {
  31. cout << cnvt.bytes[ i ] << ' ';
  32. }
  33.  
  34. // Just text conversion
  35. ostringstream cnvt2;
  36.  
  37. cnvt2 << 32.121;
  38. cout << cnvt2.str() << endl;
  39.  
  40.  
  41. cout << endl;
  42. return 0;
  43. }
  44.  
Success #stdin #stdout 0s 15240KB
stdin
Standard input is empty
stdout
Sizeof char: 1
Sizeof double: 8
s h � � |  @ @ s h � � |  @ @ 32.121