Object Bytes

Jan 11, 2011 at 12:33am
Hi.
How can I print bytes of an arbitrary object? I don't know anything about it's size. for example object is a class or a struct that I defined it.
For Example:
1
2
3
4
5
6
7
8
9
10
struct MY_STRUCT
{
   int a, b;
};

template <class T>
void print(T number); // <- This prints object T, bytes with 0 and 1
// for example: 01010101 10001000 00010001 00010001
//       => a = 01010101 10001000
//                            b = 00010001 00010001 

Thanks :-)
Jan 11, 2011 at 12:35am
To get the size, you'd use sizeof(). To print binary, make a byte to binary function. If someone doesn't post it before me, I'll try to make one.

EDIT: Finished:

1
2
3
4
5
6
7
8
9
10
template<typename T>
void print(T value){
	unsigned numbytes=sizeof(T),byte,bit;
	char* pval=(char*)&value;
	for(byte=0;byte<numbytes;++byte){
		for(bit=0;bit<8;++bit){
			putchar(((pval[byte]>>bit)&1)+'0');}
		if(byte!=numbytes-1){
			putchar(' ');}}}
Last edited on Jan 11, 2011 at 12:56am
Jan 11, 2011 at 1:53am
You realize also that this is most likely to be entirely useless information. The byte-structure of a class has relatively few caveats placed upon it -- meaning the compiler can do stuff you wouldn't expect.

Besides endianness issues, there is also padding, vtables, and, in some cases, ordering issues.
Jan 11, 2011 at 2:14am
It works with simple data types, and if he wants to change the endianness it's easy enough.

Just wondering, what would you suggest?
Last edited on Jan 11, 2011 at 2:14am
Topic archived. No new replies allowed.