Skip to content

Instantly share code, notes, and snippets.

@ladyrick
Last active July 28, 2019 08:18
Show Gist options
  • Save ladyrick/7c5532b06970e76552fe445f84e353d0 to your computer and use it in GitHub Desktop.
Save ladyrick/7c5532b06970e76552fe445f84e353d0 to your computer and use it in GitHub Desktop.
Given a variable or an object, then print the memory state. The MSB is on the left and the LSB is on the right.
#include <iostream>
#include <string>
#include <sstream>
#include <bitset>
#include <typeinfo>
using namespace std;
class cast2bits {
private:
struct bits {
unsigned char b7 : 1;
unsigned char b6 : 1;
unsigned char b5 : 1;
unsigned char b4 : 1;
unsigned char b3 : 1;
unsigned char b2 : 1;
unsigned char b1 : 1;
unsigned char b0 : 1;
};
int length;
ostringstream oss;
ostringstream data;
public:
template<class T>
explicit cast2bits(const T &input) {
data << input << " type: " << typeid(input).name();
const T *pTInput = &input;
auto *pBitsinput = (bits *) pTInput;
int n = sizeof(T) / sizeof(bits);
length = 9 * n - 1;
for (int i = n - 1; i >= 0; --i) {
oss << (int) ((pBitsinput + i)->b0)
<< (int) ((pBitsinput + i)->b1)
<< (int) ((pBitsinput + i)->b2)
<< (int) ((pBitsinput + i)->b3)
<< (int) ((pBitsinput + i)->b4)
<< (int) ((pBitsinput + i)->b5)
<< (int) ((pBitsinput + i)->b6)
<< (int) ((pBitsinput + i)->b7)
<< ' ';
}
}
friend ostream &operator<<(ostream &os, const cast2bits &c) {
os << c.data.str() << endl;
os << "M" << string((unsigned long long int) (c.length - 2), ' ') << "L" << endl;
os << c.oss.str() << endl;
return os;
}
};
int main() {
cout << cast2bits(123) << endl;
cout << cast2bits((long long) 123) << endl;
cout << cast2bits(123.0f) << endl;
cout << cast2bits(123.0) << endl;
cout << cast2bits('3') << endl;
cout << cast2bits("123") << endl;
cout << cast2bits(string("123")) << endl;
cout << cast2bits(bitset<66>().set());
return 0;
}
/* output:
123 type: i
M L
00000000 00000000 00000000 01111011
123 type: x
M L
00000000 00000000 00000000 00000000 00000000 00000000 00000000 01111011
123 type: f
M L
01000010 11110110 00000000 00000000
123 type: d
M L
01000000 01011110 11000000 00000000 00000000 00000000 00000000 00000000
3 type: c
M L
00110011
123 type: A4_c
M L
00000000 00110011 00110010 00110001
123 type: NSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEE
M L
00000000 00000000 00000000 00000000 01101111 11001010 01100110 11001101 00000000 00000000 00000000 00000000 00000000 00110011 00110010 00110001 00000000 00000000 00000000 00000000 00000000 00000000 00000000 00000011 00000000 00000000 00000000 00000000 00000000 01100010 11111011 00010000
111111111111111111111111111111111111111111111111111111111111111111 type: St6bitsetILy66EE
M L
00000000 00000000 00000000 00000011 11111111 11111111 11111111 11111111 11111111 11111111 11111111 11111111
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment