#include <iostream> #include <iomanip> using namespace std; const char *valLookup = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"; void toBase(int value, char *target, int base, int fixedDigitCount = 0) { int digitCount = 1; int temp = value; bool _signed = value < 0; // Find digit count while ( temp /= base ) digitCount++; // Compare with fixeed number of digits, use highest int i = max( fixedDigitCount, digitCount ) + _signed; // Add sign if ( _signed ) target[0] = '-'; // Convert for (int off; i - _signed; i--) { off = (value % base); value /= base; target[i-1] = valLookup[off < 0 ? -off : off]; } // Add null-ptr target[ max(fixedDigitCount, digitCount) + _signed ] = 0; } int main() { char buffer[32]; cout << "Binary with no fixed number of digits (1 to 15):\n"; for (int i = 1; i <= 15; ++i) { toBase( i, buffer, 2 ); cout << buffer << ' '; } cout << "\n\nBinary with 4 fixed digits (1 to 15):\n"; for (int i = 1; i <= 15; ++i) { toBase( i, buffer, 2, 4 ); cout << buffer << ' '; } cout << "\n\n\nOctal with no fixed number of digits (1 to 15):\n"; for (int i = 1; i <= 15; ++i) { toBase( i, buffer, 8 ); cout << buffer << ' '; } cout << "\n\nOctal with 3 fixed digits (1 to 15):\n"; for (int i = 1; i <= 15; ++i) { toBase( i, buffer, 8, 3 ); cout << buffer << ' '; } cout << "\n\n\nDecimal with no fixed number of digits (1 to 15):\n"; for (int i = 1; i <= 15; ++i) { toBase( i, buffer, 10 ); cout << buffer << ' '; } cout << "\n\nDecimal with 4 fixed digits (1 to 15):\n"; for (int i = 1; i <= 15; ++i) { toBase( i, buffer, 10, 4 ); cout << buffer << ' '; } cout << "\n\n\nHex with no fixed number of digits (1 to 15):\n"; for (int i = 1; i <= 15; ++i) { toBase( i, buffer, 16 ); cout << buffer << ' '; } cout << "\n\nHex with 2 fixed digits (1 to 15):\n"; for (int i = 1; i <= 15; ++i) { toBase( i, buffer, 16, 2 ); cout << buffer << ' '; } cin.ignore(); }