197k views
4 votes
Implement function hex2dec that takes a hex number hex_num as a string argument and prints out the corresponding decimal number. Each char in the string represents one of the 16 hex digits: '0', '1', '2', '3', ..., 'A', 'B', 'C', 'D', 'E', 'F'. No lower case letters will be used in the string. The string does not have any leading space nor the prefix "0x". For example, function call hex2dec("EF10") should print 61200. You can assume that hex_num can have up to 8 hex digits. To convert a char in the hex number string to an int, you need to check whether the char is in the range of '0' to '9'. If so, you can subtract the char by '0' to get its corresponding number. Otherwise, you need to subtract the char by 'A' and then add 10 to get its corresponding value. For example, you can use hex_num[0] - 'A' + 10 to get the int value for the most significant digit of the hex number, if the digit is between 'A' and 'F'. Restriction: printf is the ONLY C library function that you can use in the implementation.Restrictions:- printf is the ONLY C library function that you can use in the implementation (no scanf)- no pow() function - cannot add additional code to the int main() to test code - you can only call the function

User Sherwin
by
5.6k points

1 Answer

1 vote

Answer:

Check the explanation

Step-by-step explanation:

#include <iostream>

using namespace std;

void hex2dec(string hex_num){

int n = 0;

//Loop through all characters in string

for(int i=0;i<hex_num.size();i++){

//take ith character

char c = hex_num[i];

//Check if c is digit

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

n = 16*n + (c-48);

}

//Convert c to decimal

else{

n = 16*n + (c-55);

}

}

cout<<hex_num<<" : "<<n<<endl;

}

int main()

{

hex2dec("EF10");

hex2dec("AA");

return 0;

}

The Output can be seen below :

Implement function hex2dec that takes a hex number hex_num as a string argument and-example-1
User Adam Szabo
by
5.3k points