I was playing with a bunch of new things today and came up with this. Did I do anything wrong?
/*
binary class manipulator
Print values or strings as binary
by Kimberly Hamrick
*/
#include <iostream> // for C++ I/O
#include <string> // for C++ strings
using namespace std;
namespace hamrick {
template <typename T>
class binary {
public:
explicit binary( const T value, const char *sep = " " )
: _value( value ), _sep( sep ) {}
friend ostream& operator<<( ostream& os, const binary& b ) {
return b._manip_value( os, b );
}
private:
const T _value;
const char *_sep;
ostream& _manip_value( ostream& os, const binary& b ) const {
// Print each bit of the value
// Separate bytes by b._sep
for ( int bit = sizeof b._value * 8 - 1; bit >= 0; --bit ) {
os<< ( ( b._value & ( 1 << bit ) ) != 0 );
if ( bit % 8 == 0 ) os<< b._sep;
}
return os;
}
// Hide the assignment operator because of warnings
binary<T> operator=( const binary<T>& );
};
template <>
class binary<string> {
public:
explicit binary( const string& value, const char *sep = " " )
: _value( value ), _sep( sep ) {}
friend ostream& operator<<( ostream& os, const binary& b ) {
return b._manip_string( os, b );
}
private:
const string _value;
const char *_sep;
ostream& _manip_string( ostream& os, const binary& b ) const {
// Print each bit of each character
// Separate characters by b._sep
for ( const char *p = b._value.c_str(); *p != '\0'; ++p ) {
for ( int bit = 7; bit >= 0; --bit )
os<< ( ( ( *p >> bit ) & 1 ) != 0 );
os<< b._sep;
}
return os;
}
// Hide the assignment operator because of warnings
binary<string> operator=( const binary<string>& );
};
}
int main() {
cout<< hamrick::binary<int>( 1234 ) <<endl;
cout<< hamrick::binary<string>( "ABCD" ) <<endl;
for ( int a = 0; a < 256; a++ )
cout<< hamrick::binary<char>( a ) <<endl;
return 0;
}