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

I am 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); } 
+5
source share
2 answers

I would suggest offering the 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 is shown here.

+12
source

Disclaimer This is meant as a simple, frivolous solution that does not care about filling out. Prints bytes and bits from right to left.

 template<typename T> void PrintBits(const T& o) { for (size_t i = sizeof(o) - 1; i < sizeof(o); --i) std::cout << std::bitset<CHAR_BIT>(reinterpret_cast<const unsigned char*>(&o)[i]); } 
+2
source

Source: https://habr.com/ru/post/1215905/


All Articles