binary output of any type

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
#include <iostream>

void binOutput(unsigned char*,size_t);

int main()
{
	bool variable;
	binOutput((unsigned char*)&variable, sizeof(variable));
	std::cout << '\n' << variable;
	for(;;);
}

void binOutput(unsigned char* ptr, size_t size)
{
	unsigned char byte;
	for (int k=size-1;k>=0;k--)
	{
		byte = ptr[k];
		for (int n=0;n<8;n++)
		{
			std::cout << (int)((byte & 128) >> 7);
			byte <<= 1;
		}
	}
}
So I wrote this function a while ago, and I thought it was kind of neat.
You can replace bool variable; with a declaration of any type, and the output will be the binary representation of the variable or object, translated to English endian-ness (at least on Windows XP using GCC (Dev-C++), not sure if it depends on OS or compiler or both).

P.S. Let me know if you think there's a better way to do this.
I'd do

1
2
3
4
5
6
7
8
template< typename charT, typename Traits, typename T >
std::basic_ostream<charT, Traits>& tobinary( 
  std::basic_ostream<charT, Traits>& os, const T& t ) {
   T* ptr_t = reinterpret_cast<T*>( &const_cast<char&>(
       reinterpret_cast<const volatile char&>( t ) ) );

   // ... rest of your code here
}


Now you have a function that works for any type whatsoever. Of course this
isn't terribly useful if the type has pointers in it.
Topic archived. No new replies allowed.