Wednesday, November 5, 2008

Writing binary.

I read an interesting tutorial on relatively low level C programming by David Bolton on cplus.about.com. I was especially interested in the implementation of the binary printing of integers.

In the tutorial, David writes the number starting with the right-most (least significant) bit on an internal buffer which is later printed out in reverse order (from most to least significant bit from left to right). I thought that by starting with the most significant bit on the left side directly, the process could be simplified. So I have dedicated some code to the public domain, all suggestions for improvements are always welcome.
/// @brief 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
/// @date 2008-11-05.
/// @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');
  }
}