Programming Exercise: binary conversion (16 → 10)

Ideas: ASCII code into an array of integer numbers get through, Hex: 0-9 AF or af (0 ~ 15), no illegal characters into an array

The calculated index elements in the array element after the decimal value of the converted position, the summed output

※ Note ※ digital range 

//进制转换:16进制数 →十进制
//注意输入的范围
//16进制:0-9 A-F(0~15)
//逐个字符存入数组中getchar 
#include<stdio.h>
#include<math.h>
int main(){
	int a[100]={0},i,j,k;
	long long num;
	char c;
	i=0;num=0;
	while((c=getchar())!='\n'){
		if(c>='A'&&c<='F'){//A--65
			a[i]=(int)c-55;
		}
		else if(c>='a'&&c<='f'){//a--97
			a[i]=(int)c-87;
		}
		else if(c>='0'&&c<='9'){//0--48
			a[i]=(int)c-48;
		}
		else{
			i--;//非法字符不存入数组中 
		}
		i++;
	}//i最终的值为数组的实际长度 
	for(j=0;j<i;j++){
		k=i-j-1;
		num=num+a[j]*pow(16,k);
	}
	printf("%lld",num);
	return 0;
} 

 

Published 13 original articles · won praise 14 · views 5072

Guess you like

Origin blog.csdn.net/qq_37209590/article/details/104114994