C++: Example -- Convert to binary with bit ops
This program reads integers and prints them in binary,
using the shift and "and" operators to extract the relevant bits.
// Print binary representation of ints
#include <iostream>
using namespace std;
void 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
}
Problems
Here are some modifications that could be made to this code.
- It's difficult to read long sequences of digits.
It's common to put a space after every 4 digits.
- Suppress leading zeros. 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 that requires another
test.