C++ Program for Binary to Decimal and Decimal to Binary Conversion
Here is the C++ program that converts binary numbers to decimal and decimal numbers to binary:
#include <iostream>
#include <string>
using namespace std;
int binaryToDecimal(string binary) {
int decimal = 0;
int base = 1;
int len = binary.length();
for (int i = len - 1; i >= 0; i--) {
if (binary[i] != '0' && binary[i] != '1') {
return -1; // Invalid binary number
}
decimal += (binary[i] - '0') * base;
base *= 2;
}
return decimal;
}
string decimalToBinary(int decimal) {
string binary = '';
while (decimal > 0) {
binary = to_string(decimal % 2) + binary;
decimal /= 2;
}
return binary;
}
int main() {
string number;
cout << 'Enter a number: ';
cin >> number;
if (number.length() > 1 && number[0] == '0') {
// Binary to decimal conversion
if (number.length() > 9) {
cout << 'This binary number has more than 9 binary digits.' << endl;
} else {
int decimal = binaryToDecimal(number);
if (decimal == -1) {
cout << 'This is not a valid binary number.' << endl;
} else {
cout << 'Converting binary to decimal. The result is ' << decimal << endl;
}
}
} else {
// Decimal to binary conversion
int decimal = stoi(number);
if (decimal < 0 || decimal > 255) {
cout << 'This decimal number is outside the range 0 to 255.' << endl;
} else {
string binary = decimalToBinary(decimal);
cout << 'Converting decimal to binary. The result is ';
for (int i = binary.length(); i < 8; i++) {
cout << '0';
}
cout << binary.insert(4, ' ') << endl;
}
}
return 0;
}
This program uses two functions: binaryToDecimal and decimalToBinary, to convert between binary and decimal numbers. The binaryToDecimal function takes a binary string as input and returns the corresponding decimal number. The decimalToBinary function takes a decimal number as input and returns the corresponding binary string.
In the main function, the program prompts the user to enter a number. If the number has a leading zero, it is considered a binary number and is converted to decimal using the binaryToDecimal function. If the number is a valid binary number, the program displays the decimal conversion. Otherwise, it displays an appropriate error message.
If the number does not have a leading zero, it is considered a decimal number and is converted to binary using the decimalToBinary function. If the decimal number is within the range 0 to 255, the program displays the binary conversion. Otherwise, it displays an appropriate error message.
The program also checks for other error conditions such as invalid binary digits and binary numbers with more than 9 binary digits. The output is formatted according to the requirements, with leading zeros for binary numbers and a space after every 4 bits.
原文地址: https://www.cveoy.top/t/topic/bE4W 著作权归作者所有。请勿转载和采集!