fork download
  1. #include <iostream>
  2. #include <bitset>
  3. #include <climits>
  4. using namespace std;
  5.  
  6. template<typename T>
  7. void serialize_as_bin(const T &t, ostream& os) {
  8. const unsigned char *p = reinterpret_cast<const unsigned char *>(&t);
  9. for(size_t s = 0; s < sizeof t; ++s, ++p) serialize_as_bin(*p, os);
  10. }
  11.  
  12. template<>
  13. void serialize_as_bin(const unsigned char &t, ostream& os) {
  14. // Code to serialize one byte
  15. std::bitset<CHAR_BIT> x(t);
  16. os << x;
  17. }
  18.  
  19. struct Person {
  20. int a;
  21. double b;
  22.  
  23. ostream& serialize_as_binary(ostream& os) {
  24. serialize_as_bin(a, os);
  25. serialize_as_bin(b, os);
  26. return os;
  27. }
  28. };
  29.  
  30. int main() {
  31. Person p;
  32. p.a = 42;
  33. p.b = 3.14;
  34. p.serialize_as_binary(std::cout);
  35. std::cout.flush();
  36. return 0;
  37. }
Success #stdin #stdout 0s 3228KB
stdin
Standard input is empty
stdout
001010100000000000000000000000000001111110000101111010110101000110111000000111100000100101000000