Write binary
1
#include <ostream> /// Write an unsigned integral in binary base on an output stream. /// @param stream The stream to write to. /// @param value The unsigned integral value to write. /// @param digits The number of digits to write. /// @return The stream that was written to. /// @author Peter Jansson http://peter.jansson.net /// @date 2008-11-05. /// @licence Dedicated to the public domain. template<typename T> std::ostream& WriteBinary( std::ostream& stream, const T& value, const unsigned char& digits) { for( T bit( 1 << (digits-1) ); bit > 0 ; bit >>= 1 ) { stream << (( value & bit )?'1':'0'); } return stream; }
Or, if you have too little resources available:
/// Write an unsigned integral in binary base on a character buffer. /// @param value The unsigned integral value to write. /// @param digits The number of digits to write. /// @param buffer The buffer to write to. Must be at least as long /// as the number of digits to write. /// @author Peter Jansson http://peter.jansson.net /// @date 2008-11-07. /// @licence Dedicated to the public domain. template<typename T> void WriteBinary( const T& value, const unsigned char& digits, char* buffer) { for( T bit( 1 << (digits-1) ); bit > 0 ; bit >>= 1, buffer++ ) { buffer[0] = (( value & bit )?'1':'0'); } }