Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to print the bit representation of an object?

Tags:

c++

memory

I'm using something like the following. Is there a better way?

for (int i = 0; i < sizeof(Person) ; i++) {
    const char &cr = *((char*)personPtr + i);
    cout << bitset<CHAR_BIT>(cr);
}
like image 329
Sanka Darshana Avatar asked Mar 23 '15 11:03

Sanka Darshana


1 Answers

I would suggest to provide a serialize_as_binary utility in your Person class.

template<typename T>
void serialize_as_bin(const T &t, ostream& os) {
  const unsigned char *p = reinterpret_cast<const unsigned char *>(&t);
  for(size_t s = 0; s < sizeof t; ++s, ++p) serialize_as_bin(*p, os);
}

template<>
void serialize_as_bin(const unsigned char &t, ostream& os) {
  // Code to serialize one byte
  std::bitset<CHAR_BIT> x(t);
  os << x;
}

struct Person {
  A a;
  B b;

  ostream& serialize_as_binary(ostream& os) {
    serialize_as_bin(a, os);
    serialize_as_bin(b, os);
    return os;
  }
  void deserialize_from_binary() {
    // Similar stuff if required
    ...
  }
};

Live example here

like image 124
Mohit Jain Avatar answered Sep 20 '22 07:09

Mohit Jain