This is the 18th day of my participation in the November Gwen Challenge. Check out the event details: The last Gwen Challenge 2021

The principle is the same as our usual manual to hexadecimal to 10, is through the most commonly used expansion by weight method, namely the bit weight, so in order to separate the input of the hexadecimal, convenient for us to carry out the weight of each to 10, we can use a character array through the subscript to achieve this need.

Idea:

By weight expansion: (BC)H=11×16^1 + 12×16^0

Steps:

1. Use character arrays to place hexadecimal characters. 2. Place array elements in reverse order. The weight to convert characters to numbers * 16

Code implementation

float fun(int n)   // The recursive function implements 16 to the N
{
    if(n==0)
        return 1;
    else
        return  16*fun(n- 1);
}
void main(a)
{
   char s[20],*s1=s,*s2=s,*s3=s,t;
   int num;
   float sum=0.0;
     gets(s);
   while(*s1) s1++;
   for(num=s1---s; s2<s1; s2++,s1--)// Place the array elements in reverse order
           t=*s2,*s2=*s1,*s1=t;// The subscripts of array elements are used as hexadecimal weights
   while(*s3)
   {
       if(*s3=='. ')
           break;
       s3++;
   }
   for(s1=s; s1<s+num; s1++) {if(s1-s3<0&&*s3=='. ')                  *s3='.'
        {
            if(*s1>=48&&*s1<=57)              // Determine the weight of 16 according to the subscript of the decimal point
                sum=sum+(*s1- 48)/fun(s3-s1);   // Convert characters to numbers * 16 weight
            else  if(*s1>='A'&&*s1<='Z')
                sum=sum+(*s1- 55)/fun(s3-s1);
            else  if (*s1>='a'&&*s1<='z')
                sum=sum+(*s1- 87.)/fun(s3-s1);
        }
        else  if(*s3=='. ')                        *s3='.'
        {
            if(*s1>=48&&*s1<=57)                 // Determine the weight of 16 according to the subscript of the decimal point
                sum=sum+(*s1- 48)*fun(s1-s3- 1);    // Convert characters to numbers * 16 weight
            else  if(*s1>='A'&&*s1<='Z')
                sum=sum+(*s1- 55)*fun(s1-s3- 1);
            else  if (*s1>='a'&&*s1<='z')
                sum=sum+(*s1- 87.)*fun(s1-s3- 1);
        }
        else
        {
            if(*s1>=48 && *s1<=57)         // Convert characters to numbers * 16 weight
                sum=sum+(*s1- 48)*fun(s1-s);
            else  if(*s1>='A'&&*s1<='Z')
                sum=sum+(*s1- 55)*fun(s1-s);
            else  if (*s1>='a'&&*s1<='z')
                sum=sum+(*s1- 87.)*fun(s1-s); }}printf("%f",sum);
}
Copy the code