c语言将16进制转换成10进制

前言

要转换的字符串中包含可选的前缀0x或者0X,

代码

/*
 * Created by sutaoyu on 2018/10/2
 *
 */
#include<stdio.h>
#include<ctype.h>

#define YES 1
#define NO 0


int htoi(char s[])
{
    int hexdigit, i, inhex, n;
    i = 0;
    if (s[i] == '0')
    {
        ++i;
        if (s[i] == 'x' || s[i] == 'X')
        {
            ++i;
        }
    }
    n = 0;
    inhex = YES;
    for ( ; inhex == YES; ++i)
    {
        if (s[i] >= '0' && s[i] <= '9')
        {
            hexdigit = s[i] - '0';
        }
        else if (tolower(s[i]) >= 'a' && tolower(s[i]) <= 'z')
        {
            hexdigit = s[i] - 'a' + 10;
        }
        else
        {
            inhex = NO;
        }
        if (inhex == YES)
        {
            n = 16 * n + hexdigit;
        }
    }
    return n;
}


int main()
{
    char s[100];
    scanf("%s", s);
    printf("char is %s\n", s);
    printf("integer is %d\n", htoi(s));
    return 0;
}
已标记关键词 清除标记
相关推荐
©️2020 CSDN 皮肤主题: 代码科技 设计师:Amelia_0503 返回首页