C++ Notes: Bit Ops - Convert to binary

This program reads integers and prints them in binary, using the shift and "and" operators to extract the relevant bits.
  1 
  2 
  3 
  4 
  5 
  6 
  7 
  8 
  9 
 10 
 11 
 12 
 13 
 14 
 15 
 16 
 17 
 18 
 19 
 20 
 21 
// to-binary-bitops.cpp  Print binary representation of ints
// Fred Swartz  - 2001-09-04

#include <iostream>
using namespace std;

int main() {
    int n;
    while (cin >> n) {
        cout << "decimal: " << n << endl;

        // print binary with leading zeros
        cout << "binary : ";
        for (int i=31; i>=0; i--) {
            int bit = ((n >> i) & 1);
            cout << bit;
        }
        cout << endl;
    }//end loop
    return 0;
}//end main

Programming assignments

Here are some possible improvements.
  1. It's difficult to read long sequences of bits. Put a space after every 4 digits (a common style). Hint: The idiom for doing this is to use the mod (%) operator to do something every nth time.
  2. Suppress leading zeros. Hint: This is done most easily by defining a bool flag, setting it to false at the beginning of each conversion, setting it to true when a non-zero bit is encountered, and printing zeros only when this flag is set to true. Then there's the case of all zeros. Be sure that the number 0 prints correctly.
  3. This program assumes ints are 32 bits. Altho this is now the most common size, the C++ specification allows other sizes. I've personally used machines where the int sizes were 16, 19, 32, 36, and 60 bits. Hint: use sizeof.
  4. This is a simple demonstration program, but a conversion like this should be written as a utility function that returns a character string representation. This raises several tougher issues: