// demo_02_ascii_byte_2_binary.cpp
/*
* @topic T00242 Binary numbers
* @brief <br />A program to convert integer to its binary representation<br /><br />
*/
#include <iostream>
int main()
{
for (;;) {
// forever -- endless loop
//char ch = 'A'; // this works, too
int ch;
std::cout << "Enter a number: ";
std::cin >> ch;
const unsigned int BIT_COUNT = sizeof( ch ) * 8; // how many bits are there?
unsigned int bit_mask = ( 1 << ( BIT_COUNT - 1 ) ); // set highest bit to 1
// starting with the leftmost bit, display 0 or 1 on the screen:
int idx = 0;
for ( ; idx < BIT_COUNT; ++idx ) {
if ( idx % 8 == 0 ) std::cout << ' '; // separate each byte by space
if ( ch & bit_mask ) std::cout << '1'; else std::cout << '0';
bit_mask = bit_mask >> 1; // shift bits to the right
}
std::cout << '\n';
}//forever
return 0;
}