1. 程式人生 > >十六進位制轉換為十進位制

十六進位制轉換為十進位制

#include<stdio.h>
#define MAX 100
int main()
{ 
	int trans(char *s);
	int c,i=0;
	char t[MAX];
	printf("請輸入一個十六進位制的數:");
	while((c=getchar()) !='\0' && i<MAX)
	{  
		if(c >= '0' && c <= '9' || c >= 'a' && c <= 'f'|| c >= 'A' && c<= 'F')
			t[i++]=c;
		else 
		{
			t[i]='\0';
			printf("十進位制數為:%d\n",trans(t));
			break;
		}
	}
	return 0;
}
int trans(char *s)
{
	int i,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;
}