Write a program to convert a 4 digit hexadecimal number into decimal. The user s
ID: 3887078 • Letter: W
Question
Write a program to convert a 4 digit hexadecimal number into decimal. The user should be instructed to enter a 4-digit hexadecimal number. The corresponding decimal number (0 to 65,535) should be output. Note that the place values for a 4-digit hexadecimal number from left to right are 4096, 256, then 16, then 1. You must input the Hexadecimal number as a String, then use the charAt(N) method to compare each individual character to 'A', 'B', 'C', 'D', 'E', 'F' and '0' through '9', and add the value of the digit times the corresponding place value to the total.
For example, 1A3016 = 1*4096+10*256+3*16+0*1 = 670410
First, prompt for and input a String of four characters.
If the input is not four characters, print out an appropriate message and exit.
Use if statements, each meaning something like "If the second character is equal to 'A', the value of the second digit is 256 * 10". If any character is not '0'-'9' or 'A'-'F', print out an appropriate message and exit.
In order to compare each character of the input String to a char, use ==, and be sure to use single quotes rather than double quotes.
You cannot use any built-in conversion methods for this program.
Explanation / Answer
#include <stdio.h>
#include <math.h>
#include <string.h>
int main()
{
char hex[17];
long long decimal, place;
int i = 0, val, len;
decimal = 0;
place = 1;
/* Input hexadecimal number from user */
printf("Enter any hexadecimal number: ");
gets(hex);
/* Find the length of total number of hex digit */
len = strlen(hex);
len--;
/*
* Iterate over each hex digit
*/
for(i=0; hex[i]!=''; i++)
{
/* Find the decimal representation of hex[i] */
if(hex[i]>='0' && hex[i]<='9')
{
val = hex[i] - 48;
}
else if(hex[i]>='a' && hex[i]<='f')
{
val = hex[i] - 97 + 10;
}
else if(hex[i]>='A' && hex[i]<='F')
{
val = hex[i] - 65 + 10;
}
decimal += val * pow(16, len);
len--;
}
printf("Hexadecimal number = %s ", hex);
printf("Decimal number = %lld", decimal);
return 0;
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.