Untitled
unknown
c_cpp
2 years ago
1.6 kB
6
Indexable
#include <iostream>
#include <limits> // For numeric_limits
using namespace std;
void convert(int decimal) {
if (decimal < 0) {
cout << "Error: Negative input is not supported." << endl;
return;
}
string binary, octal, hexa;
while (decimal > 0) {
// Binary conversion (more efficient with bitwise AND)
binary = to_string(decimal & 1) + binary;
decimal >>= 1; // Right shift by 1 (equivalent to division by 2)
// Octal conversion
octal = to_string(decimal % 8) + octal;
decimal /= 8; // Division by 8
// Hexadecimal conversion
int hexcode = decimal % 16;
if (hexcode >= 10) {
hexa = (char)(hexcode - 10 + 'A') + hexa; // Use character casting for hex digits
} else {
hexa = to_string(hexcode) + hexa;
}
decimal /= 16;
}
cout << "\nBinary: " << binary;
cout << "\nOctal: " << octal;
cout << "\nHexadecimal: " << hexa << endl;
}
int main() {
int decimal;
char choice;
do {
cout << "Enter decimal number: ";
if (!(cin >> decimal)) {
cout << "Invalid input. Please enter a number." << endl;
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(), '\n'); // Clear input buffer
} else {
convert(decimal);
cout << "\n-----------\n";
cout << "Convert again? [y/n]: ";
cin >> choice;
}
} while (choice == 'y' || choice == 'Y'); // Allow both uppercase and lowercase 'y'
return 0;
}
Editor is loading...
Leave a Comment