hexadecimal string to decimal number C code

Source: Internet
Author: User
Tags pow

#include <stdio.h>
#include <math.h>

int main ()
{
Char ch;//is used to accept an input character
int stack[50];//the hexadecimal decimal corresponding to the stored processing
The number of data in the int top=0;//stack
int decimal=0;//The position of the decimal point in the input string, counting starting at number No. 0
Float num=0;//calculates the last decimal number

printf ("Please enter Hex (0-9,a-f,a-f):");
while ((Ch=getchar ())!= '/n ')
{
if (ch>= ' 0 ' &&ch<= ' 9 ')
Stack[top++]=int (ch-48);
else if (ch>= ' A ' &&ch<= ' F ')
Stack[top++]=int (ch-55);
else if (ch>= ' a ' &&ch<= ' F ')
Stack[top++]=int (ch-87);
else if (ch== '. ') If it's a decimal point
decimal=top;//indicates that data from the decimal data is a small number of parts
else {
printf ("entered illegal data");
return 0;
}
}

while (top)
{
if (decimal!=0&&top>decimal)//Calculation of the decimal part
Num+=stack[--top]/pow (16,top-decimal+1);
Else
Num+=stack[--top]*pow (16,top)//To calculate the whole number of parts
}
printf ("%.4f", num);
GetChar ();
return 1;
}

March 17, 2009, reserved for remembrance.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.