#include #include #include #include #include #include using namespace std; int bin2dec(char *n); int hex2dec(char *n); int oct2dec(char *n); void inputInt(int &n); bool inBinCheck(char n[]); bool inOctCheck(char n[]); bool inHexCheck(char n[]); int main(){ bool loop = true; char ch; char n[20]; int choice; while(loop){ printf("1. Convert binary number to decimal number\n2. Convert octal number to decimal number\n3. Convert hexadecimal number to decimal number\n4. Exit\n"); printf("Please choose number (1 - 4): "); while(1){ inputInt(choice); if(choice >= 1 && choice <= 4) break; printf("Wrong input! Try again...\n"); } switch (choice){ case 1: printf("Enter binary number: "); while(!inBinCheck(n)) printf("\nPlease input correct form of binary!\nTry again: "); printf("Decimal number is: %d", bin2dec(n)); break; case 2: printf("Enter octal number: "); while(!inOctCheck(n)) printf("\nPlease input correct form of octal!\nTry again: "); printf("Decimal number is: %d", oct2dec(n)); break; case 3: printf("Enter hexadecimal number: "); while(!inHexCheck(n)) printf("\nPlease input correct form of hexadecimal!\nTry again: "); printf("Decimal number is: %d", hex2dec(n)); break; case 4: printf("Closing...\nThankyou for using Program!<3"); exit(1); break; } printf("\nPress enter to continue, Esc to return the main menu\n"); ch = getch(); if(ch == 27) loop = false; } printf("\nThankyou for using Program!<3"); } int bin2dec(char n[]){ int dec = 0; int length = strlen(n) - 1; for(int i = 0, j = length;i < strlen(n); i++, j--){ int temp = n[j] - 48; dec += temp * pow(2,i); } return dec; } int hex2dec(char n[]){ int dec = 0; int arrCount = strlen(n) - 1; for(int i = 0, j = arrCount;i < strlen(n); i++, j--){ int temp; if(isdigit(n[j])) temp = n[j] - 48; else if(isupper(n[j])) temp = n[j] - 55; else if(islower(n[j])) temp = n[j] - 87; dec += temp * pow(16,i); } return dec; } int oct2dec(char n[]){ int dec = 0; int arrCount = strlen(n) - 1; for(int i = 0, j = arrCount;i < strlen(n); i++, j--){ int temp; temp = n[j] - 48; dec += temp * pow(8,i); } return dec; } bool inBinCheck(char n[]){ gets(n); for(int i = 0; i < strlen(n); i++){ if(n[i] == 48 || n[i] == 49) continue; else return false; } return true; } bool inOctCheck(char n[]){ gets(n); for(int i = 0; i < strlen(n); i++){ if(n[i] >= 48 && n[i] <= 55) continue; else return false; } return true; } bool inHexCheck(char n[]){ gets(n); for(int i = 0; i < strlen(n); i++){ if(n[i] >= 49 && n[i] <= 57) continue; else if(n[i] >= 65 && n[i] <= 70) continue; else if(n[i] >= 97 && n[i] <= 102) continue; else return false; } return true; } void inputInt(int &n){ bool loop = true; while(loop){ scanf("%d", &n); if(!isspace(getchar())){ fflush(stdin); printf("Wrong input! Try again...\n"); // continue; } else loop = false; } }