Write a program in C or C++ which takes as input a string representation of an u
ID: 3795924 • Letter: W
Question
Write a program in C or C++ which takes as input a string representation of an unsigned hexadecimal number in 32 bits and returns the positive integer that is the base 10 equivalent. You do not need to worry about negative values for this question You can use a dictionary, or brute force to convert hex digits to numbers (i.e. write a function with a bunch of if statements or a select statement to deal with digits A-F. or store the values 0-F as keys in a dictionary with the values being the number the digit represents.
Explanation / Answer
#include <stdio.h>
#include <math.h>
#include <string.h>
int main()
{
char hexnumber[17];//to store hex number
int i = 0, final, length;
long long dec, place;
dec = 0;
place = 1;
printf("Enter Hex number: ");
gets(hexnumber);//accept hex number
length = strlen(hexnumber); //get length of number
length--;
for(i=0; hexnumber[i]!=''; i++)
{
switch(hexnumber[i])//check number and letters in hex number and assign decimal number
{
case '0':
final = 0;
break;
case '1':
final = 1;
break;
case '2':
final = 2;
break;
case '3':
final = 3;
break;
case '4':
final = 4;
break;
case '5':
final = 5;
break;
case '6':
final = 6;
break;
case '7':
final = 7;
break;
case '8':
final = 8;
break;
case '9':
final = 9;
break;
case 'a':
case 'A':
final = 10;
break;
case 'b':
case 'B':
final = 11;
break;
case 'c':
case 'C':
final = 12;
break;
case 'd':
case 'D':
final = 13;
break;
case 'e':
case 'E':
final = 14;
break;
case 'f':
case 'F':
final = 15;
break;
}
dec += final * pow(16, length);//convert and to decimal number
length--;
}
printf(" hexadecimal number is = %s ", hexnumber);
printf("and its decimal number is= %lld", dec);
return 0;
}
=====================================================================================
Output:
akshay@akshay-Inspiron-3537:~/Chegg$ ./a.out
Enter Hex number: F
hexadecimal number is = F
and its decimal number is= 15
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.