Converting a string to binary


Match word(s).

If you have any questions or comments,
please visit us on the Forums.

FAQ > How do I... (Level 3) > Converting a string to binary

This item was added on: 2003/03/22

In C++ you can use two handy dandy template functions to reverse and show the bits in a value. The print_bits function writes the bits in a value in reverse order to stdout for simplicity. The rev_bits function does just that, so that print_bits shows a more viewer friendly bit pattern.


#include <iostream> 
#include <climits> 
#include <string> 

template <typename T>
void print_bits ( T val )
{
  unsigned int n_bits = sizeof ( val ) * CHAR_BIT;

  for ( unsigned i = 0; i < n_bits; ++i ) {
    std::cout<< !!( val & 1 );
    val >>= 1;
  }
}

template <typename T>
T rev_bits ( T val )
{
  T ret = 0;
  unsigned int n_bits = sizeof ( val ) * CHAR_BIT;

  for ( unsigned i = 0; i < n_bits; ++i ) {
    ret = ( ret << 1 ) | ( val & 1 );
    val >>= 1;
  }

  return ret;
}

int main()
{
  std::string s = "This is a test";
  std::string::iterator it;

  for ( it = s.begin(); it != s.end(); it++ ) {
    print_bits ( rev_bits ( *it ) );
    std::cout<<"  "<< *it <<std::endl;
  }

  return 0;
}

/*
 * Output:
 01010100  T
 01101000  h
 01101001  i
 01110011  s
 00100000
 01101001  i
 01110011  s
 00100000
 01100001  a
 00100000
 01110100  t
 01100101  e
 01110011  s
 01110100  t
 *
 */

Credit: Prelude

Script provided by SmartCGIs