16 specific algorithm for converting binary to decimal is:
(1) First of all, understand that 16 number ( from right to left the No. 0, 1th, 2nd – ) weights for No. 0 - 0 16, 1th - 1 of the weight of 16, the 2nd - 2 of the weight is 16, and then click Arrange it.
(2) See binary number represented by the ABCDEF is 10,11,12,13,14,15.
(3) 16 is the formula for converting binary to decimal : from right to left, with each binary number multiplied by 16 of the appropriate party, and then just numbers.
// date:2020/3/4
// author:xiezhg5
#include <stdio.h>
#define MAX 1000 //宏定义
int main(void)
{
int change(char s[]); //定义change函数用于进制转换
int c,i,flag,flag1;
char t[MAX];
i=0; //控制变量i
flag=0; //目标变量flag
flag1=1; //flag判断变量
printf("请输入一个十六进制数:\n");
while((c=getchar())!='\0'&&i<MAX&&flag1) //getchar()函数
{
if(c>='0'&&c<='9'||c>='a'&&c<='f'||c>='A'&&c<='F')
{
flag=1;
t[i++]=c; //将c的值储存在数组t[i++]中符合人们习惯(不是t[i])
}
else if(flag)
{
t[i]='\0';
printf("十进制数:%d\n",change(t)); //调用change函数
printf("继续或终止?\n");
c=getchar();
//if--else嵌套 cx
if(c=='N'||c=='n') //(终止情况)
flag1=0;
else //(继续情况)
{
flag=0;
i=0;
printf("请输入一个十六进制数:\n");
}
}
}
}
int change(char s[])
{
int i,n;
n=0;
for(i=0;s[i]!='\0';i++)
{
//十六进制转十进制核心算法
if(s[i]>='0'&&s[i]<='9')
n=n*16+s[i]-'0';
if(s[i]>='a'&&s[i]<='f')
n=n*16+s[i]-'a'+10;
if(s[i]>='A'&&s[i]<='F')
n=n*16+s[i]-'A'+10;
}
return(n);
}