十六进制以内任意进制数转十进制

十六进制以内任意进制数转十进制的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;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值