/* * @topic T00245 Binary numbers * @brief <br /><span style="background-color: yellow;">New: </span> Convert number to binary notation<br /> */ #include <iostream> void char_2_binary( char ch ); // function declaration void int_2_binary( unsigned int value ); int main() { for(;;) { std::cout << "Please type a number: "; int number; std::cin >> number; int_2_binary( number ); } return 0; } void int_2_binary( unsigned int value ) { // calculate number of bits in int unsigned int bit_count = sizeof(int) * 8; // create a bit mask with highest bit set to 1, e.g. 10000000 unsigned int bit_mask = 1; bit_mask = bit_mask << (bit_count - 1); for ( ; bit_count > 0; --bit_count ) { // display space after every 8th digit: if ( bit_count % 8 == 0 ) std::cout << ' '; // display 1 or 0 for each bit indicated by the mask if ( value & bit_mask ) std::cout << '1'; else std::cout << '0'; //bit_mask = bit_mask / 2; // shift bits to the left using integer division bit_mask = bit_mask >> 1; // shift bits to the left using bit shift op } std::cout << '\n'; }