47.2k views
5 votes
Defining a hexadecimal number as in Problem 67, write the function int hexToDec( const int hexNum[]) to convert a four-digit hexadecimal number to a nonnegative decimal integer. Do not output the decimal integer in the function. Test your function with interactive input.

User Shakeria
by
7.8k points

1 Answer

5 votes

Answer:

#include <stdio.h>

int hexToDec(const int hexNum[]){

int result = 0, prod = 1;

for(int i = 3;i>=0;i-=1){

result += (prod*hexNum[i]);

prod = prod * 16;

}

return result;

}

int main()

{

int hexNum[4], i;

char s[5], ch;

printf("Enter hexa decimal value: ");

scanf("%s",s);

for(i = 0;i<4;i++){

ch = s[i];

if(ch>='0' && ch<='9'){

hexNum[i] = ch-'0';

}

else if((ch>='a' && ch<='f') || (ch>='A' && ch<='F')){

if(ch=='A' || ch=='a'){

hexNum[i] = 10;

}

else if(ch=='B' || ch=='b'){

hexNum[i] = 11;

}

else if(ch=='C' || ch=='c'){

hexNum[i] = 12;

}

else if(ch=='D' || ch=='d'){

hexNum[i] = 13;

}

else if(ch=='E' || ch=='e'){

hexNum[i] = 14;

}

else{

hexNum[i] = 15;

}

}

}

printf("%d",hexToDec(hexNum));

return 0;

}

Step-by-step explanation:

User Andre Hofmeister
by
9.3k points