Two implementations of hexadecimal to decimal in C language

  • 2020-05-10 18:35:59
  • OfStack

C language · base 106 to base 10

Problem description

Input a string of a positive base 106 number no more than 8 bits from the keyboard, convert it to a positive base 10 number and output it.

Note: in base 106 Numbers, 10 to 15 are expressed in uppercase letters A, B, C, D, E, F.

The sample input

FFFF

Sample output

65535

Train of thought: feel oneself of the following two methods are right, but...... don't say [cunning]...

Plan 1:


#include<stdio.h>
#include<math.h>
#include<string.h>
int main(){
char s[50];
scanf("%s",s);
int t=strlen(s);
long sum=0;
for(int i=0;i<t;i++){
if(s[i]>='A' && s[i]<='Z')
s[i]=int(s[i]-'A')+10+'0';
sum+=((s[i]-'0')*(pow(16,t-1-i)));
}
printf("%ld\n",sum);
}

Scheme 2:


#include<stdio.h>
int main(){
char s[50];
scanf("%s",s);
int t;
long sum=0;
for(int i=0;s[i];i++){
if(s[i]<='9')
t=s[i]-'0';
else
t=s[i]-'A'+10;
sum=sum*16+t;
}
printf("%ld\n",sum);
return 0;
}

  thanks for reading, hope to help you, thank you for your support!


Related articles: