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;
}
Credit: Prelude