十六进制转换为十进制

/* 2、编写函数htoi(s),把由十六进制数字组成的字符串(包含可选的前缀0x或0X)转换为与之等价的整形值。
字符串中允许包含的数字包括:0~9,a~f以及A- F 。 */

#include
#include
#include
#include "my_type.h"

int32_t exchange(char_t c);
int32_t htoi(const char_t s[]);
int32_t main();


int32_t main()
{
for(;;)
{
int32_t decimalism=0,b=0,c=0,d=0,j=0;
uint32_t len,i;
char_t str[10];
printf("please input a string(the range of string length is (0-8)),input 'ENTER_KEY' exit:\n");
gets(str);
len=strlen(str);
printf("\n");
if((str[0]!='0')&&((str[1]!='x')||(str[1]!='X')))
{
for (i=(uint32_t)0;i{
if(str[0]=='-')
{
j=1;
b=exchange(str[j]);
if(b==-1)
{
c++;
}
j++;
}
else
{
b=exchange(str[i]);
if(b==-1)
{
d++;
}
}
}
}
decimalism=htoi(str);
if((len>((uint32_t)8))||((str[0]=='0')&&((str[1]=='x')||(str[1]=='X'))&&(len==((uint32_t)2)))||((c>=1)||(d>=1)))
{
printf("input error,please input again!!\n");
system("pause");
system("cls");
}
else if ((len== ((uint32_t)0)))
{
break;
}
else
{
printf("%d\n",decimalism);
system("pause");
system("cls");
}
}
exit (0);
}

int32_t exchange(char_t c) /* 将“0-9”、“a-f”、“A-F” */
{ /* 的单字符转换成十进制 */

int32_t n=0;
if(((int32_t)c<='9') && ((int32_t)c>='0'))
{
n=(int32_t)c-'0';
}
else if(((int32_t)c<='f') && ((int32_t)c>='a'))
{
n=((int32_t)c-'a')+10;
}
else if(((int32_t)c<='F') && ((int32_t)c>='A'))
{
n=((int32_t)c-'A')+10;
}
else
{
n=-1;
}
return (n);
}

int32_t htoi(const char_t s[])
{
int32_t len,t,count=0,num=0;
len=(int32_t)strlen(s); /* 得到字符串的长度 */
if((s[0]=='0')&&((s[1]=='x')||(s[1]=='X')))
{
for(count=0;count<(len-2);count++)
{
t=exchange(s[count+2]);
if(t!=-1)
{
num=(num*16)+t; /* 十六进制的字符串转换十进制的转换公式 */
} /* 假设十六进制字符串为“abcdef */
} /* 则十进制数=((((a*16+b)*16+c)*16+d)*16+e)*16+f */
}
else if(s[0]=='-')
{
for(count=0;count<(len-1);count++)
{
t=exchange(s[count+1]);
if(t!=-1)
{
num=(num*16)+t;
}
}
num=-num;
}
else
{
for(count=0;count{
t=exchange(s[count]);
if(t!=-1)
{
num=(num*16)+t;
}
}
}
return (num);
}

相关文档
最新文档