#include #include #include using namespace std; long address2long(const void* address); unsigned powerOf2(int exp); template void printBits(T type); struct Struct1 { char c1; char c2; short s1; int i; }; ostream& operator<<(ostream& out, const Struct1& d) { out << "Address: " << address2long(&d) << " " << sizeof(d) << " bytes" << endl; out << " &c1: " << address2long(&d.c1); printBits(d.c1); out << " &c2: " << address2long(&d.c2); printBits(d.c2); out << " &s1: " << address2long(&d.s1); printBits(d.s1); out << " &i: " << address2long(&d.i); printBits(d.i); return out; } struct Struct2 { char c1; int i; char c2; short s1; }; ostream& operator<<(ostream& out, const Struct2& d) { out << "Address: " << address2long(&d) << " " << sizeof(d) << " bytes" << endl; out << " &c1: " << address2long(&d.c1); printBits(d.c1); out << " &i: " << address2long(&d.i); printBits(d.i); out << " &c2: " << address2long(&d.c2); printBits(d.c2); out << " &s1: " << address2long(&d.s1); printBits(d.s1); return out; } int main() { Struct1 s1 = {'A','B',static_cast(13),55}; printBits(s1); cout << endl; Struct2 s2 = {'A',55,'B',static_cast(13)}; printBits(s2); } long address2long(const void* address) { return reinterpret_cast(address); } template void printBits(T t) { cout << setw(6) << t << " "; unsigned mask; unsigned char* ptr; for (size_t i = 0; i < sizeof(T); i++) { // Advance ptr each byte of the argument ptr = reinterpret_cast(&t) + i; // Print the contents of the byte for (int i = 7; i >= 0; --i) { mask = powerOf2(i); cout << (*ptr & mask ? 1 : 0); } cout << " "; } cout << endl; } unsigned powerOf2(int exp) { unsigned value = 1; for (int i = 0; i < exp; ++i) { value *= 2; } return value; }