1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
|
// to-binary-reversed.cpp - Convert decimal to binary by repeated mod, div.
// Fred Swartz - 2001-09-04
// This algorithm prints the bits from low to high order.
// Improvements on the order have to wait until
// bit operations, arrays or strings, functions, etc
// Doesn't work with negative numbers or zero.
#include <iostream>
using namespace std;
int main() {
int n; // number to convert to binary
while (cin >> n) {
if (n > 0) {
cout << n << " (decimal) = ";
while (n > 0) {
cout << n%2;
n = n/2;
}
cout << " (binary) in reverse order" << endl;
} else {
cout << "Please enter a number greater than zero." << endl;
}
}
return 0;
}//end main
The text from the above example can be selected, copied, and pasted into an editor.
|