#include #include using namespace std; const char* BINARY_DIGITS = "01"; void int2bin(int n, char* txt); int main() { char txt[64]; while (true) { int n; cout << "Enter an integer number (q for the end):" << endl; if (!(cin >> n)) break; int2bin(n, txt); cout << "Binary representation: " << txt << endl; } return 0; } void int2bin(int n, char* txt) { if (n == 0) { txt[0] = '0'; txt[1] = 0; return; } char* pos = txt; if (n < 0) { *pos = '-'; ++pos; n = (-n); } char* beg = pos; assert(n > 0); while (n != 0) { int r = n%2; assert(0 <= r && r < 2); *pos = BINARY_DIGITS[r]; ++pos; n /= 2; } *pos = 0; // Terminate the text string // Invert the text --pos; while (beg < pos) { // Swap two digits char tmp = *beg; *beg = *pos; *pos = tmp; ++beg; --pos; } }