十六进制以内任意进制数转十进制的C语言实现
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
#include <unistd.h>
int parseInt(char *str, int type)
{
int value = 0;
//int length = strlen(str) - 1;
char tmpChar;
while((tmpChar = *str) != '\0')
{
//printf("tmpChar:%c\n", tmpChar);
//出现不符合的字符直接返回
//48-57(0-9), 65-90(A-Z), 97-122(a-z), [45(-), 46(.)]
if((tmpChar >= 48 && tmpChar <= 57) || (tmpChar >= 65 && tmpChar <= 90)
|| (tmpChar >= 97 && tmpChar <= 122))
{
//只处理十六进制以内的进制数
if(type > 16)
{
return -2;
}
if(type == 16)
{
if(tmpChar >= 'A' && tmpChar <= 'F')
{
tmpChar = tmpChar - 'A' + 10;
}
else if(tmpChar >= 'a' && tmpChar <= 'f')
{
tmpChar = tmpChar - 'a' + 10;
}
else
{
tmpChar -= '0';
}
}
else
{
tmpChar -= '0';
}
//printf("tmpChar:%d\n", tmpChar);
//printf("length:%d\n", length);
//value += tmpChar * pow(type, length--);//效率低下
value = value * type + tmpChar;
str += 1;
}
else
{
return -1;
}
}
return value;
}
int main()
{
char str[] = "22222";
int ret = parseInt(str, 8);
if(ret == -1)
{
printf("出现非法字符!\n");
return 1;
}
if(ret == -2)
{
printf("只能处理十六进制以内的数据!\n");
return 1;
}
printf("输入的整型数为:%d\n", ret);
return 0;
}