/* * @topic S-0312-07-03-12 print bits of a character * @brief power of 2, binary numbers, C++ functions */ #include <cstdlib> #include <iostream> #include <cmath> using namespace std; int power( int value, int exp ) { int result = 1; //while (exp--) result = result * value; while (exp--) result *= value; return result; }//power void print_binary_char_hardcoded( char ch ) { cout << ( ( ch & 128 ) != 0 ); // 128 == power( 2, 7 ) cout << ( ( ch & 64 ) != 0 ); // 64 == power( 2, 6 ) cout << ( ( ch & 32 ) != 0 ); // 32 == power( 2, 5 ) cout << ( ( ch & 16 ) != 0 ); // 16 == power( 2, 4 ) cout << ( ( ch & 8 ) != 0 ); // 8 == power( 2, 3 ) cout << ( ( ch & 4 ) != 0 ); // 4 == power( 2, 2 ) cout << ( ( ch & 2 ) != 0 ); // 2 == power( 2, 1 ) cout << ( ( ch & 1 ) != 0 ); // 1 == power( 2, 0 ) cout << "\n"; }//print_binary_char_hardcoded void print_binary_char( char ch ) { for (int bit_count = 8; bit_count; --bit_count ) { cout << ( ( ch & power( 2, bit_count - 1 ) ) != 0 ); } cout << "\n"; }//print_binary_char int main() { char ch; cout << "enter a character: "; while ( cin >> ch ) { print_binary_char( ch ); cout << "\nenter a character: "; } system( "pause" ); return 0; }//main