I have been struggling trying to convert hexadecimal to binary. I was assigned to write a piece of code that calculates the output of a full-adder circuit. Part of the assignment is determining the base in which the numbers are being entered by the user. I have been testing whether my code was working or not and I have noticed something rather odd in hexadecimal converter.
If I enter any character that has a higher value than "F" returns the expected "Not a hexadecimal" error.
If I enter any character between "8" and "F"(both are included) I get the expected "Cannot represent with 3 binary digits" error.
I also get the expected binary values for all the numbers except "2" and "3"... I don't know what could be causing this unexpected behaviour. Any help is appreciated. You can try to run it yourself in order to understand the code better but here is my output:
0 0
1 1
2 8
3 9
4 100
5 101
6 110
7 111
8-F Cannot represent with 3 bits.
>F Not a hexadecimal.
Here is the code:
#include<stdio.h>
#include <ctype.h>
int main(){
int optionChosen,binaryNum,reset;
char hexadecimal;
while (true){
printf("Please enter input: ");
fflush(stdin); //This line clears the input buffer
//Note: using fflush(stdin) is undefined and is told to be avoided whenever possible
scanf("%c",&hexadecimal);
hexadecimal=toupper(hexadecimal);
if (hexadecimal>'F'){
//Print an error message if the option chosen by the user is out of range.
printf("Value out of range! Please enter a valid value (0-F)\n");
}
else{
reset=0;//This is placed here so that the program does not ask for input all the time
switch (hexadecimal){//using a switch to convert hexadecimal to binary
case '0':
binaryNum=000;
break;
case '1':
binaryNum=001;
break;
case '2':
binaryNum=010;
break;
case '3':
binaryNum=011;
break;
case '4':
binaryNum=100;
break;
case '5':
binaryNum=101;
break;
case '6':
binaryNum=110;
break;
case '7':
binaryNum=111;
break;
default:
//return error message if default value is entered.
reset=1;//This makes sure the user is asked to enter input again.
printf("Hexadecimal %c cannot be represented with 3 bits!Please try again \n",hexadecimal);
}
if (reset==0){//This breaks the loop and continues with the rest of the code if the user value is in range
printf("binaryNum = %d\n",binaryNum);
}
}
}
return 0;
}