经典案例--十六进制转换为十进制

1、方法一 用一级指针

#include 
#include 
#include 

int convert(char *myp, int mylen, int *Poutput)
    {
    int i = 0;
    char *pstart = myp + 1;
    char *Pstop = myp + mylen - 1;
    int ant = 0;
    int hex = 1;

    if(Pstop == NULL )
    {
        return -1;
    }

    if(myp == NULL)
        {
        return -1;
    }

    while(Pstop > pstart)
        {
        for(i = 0; i < mylen - 2; i++)
            {
            if(*Pstop >= 'A' && *Pstop <= 'F')
                {
                ant = ant + (*Pstop - 'A' + 10) * hex;
            }
            else
                {
                ant = ant + (*Pstop - '0') * hex;
                }
                Pstop --;
                hex = hex * 16;
            }
    }
    *Poutput = ant;
    return 0;
}

int main()
    {
    char buf1[10];
    int  output = 0;
    int len = 0;
    int ret = 0;

    scanf("%s",buf1);
    len = strlen(buf1);
    ret = convert(buf1,len,&output);
    if(ret != 0)
        {
        printf("func convert() error!");
        return ret;
    }
    printf("output:%d \n",output);
    return 0;
}


2、方法二 用二级指针

#include 
#include 
#include 

int convert(char *myp, int mylen, int **Poutput)
    {
    int i = 0;
    char *pstart = myp + 1;
    char *Pstop = myp + mylen - 1;
    int ant = 0;
    int hex = 1;
    int *tmp = NULL;

    tmp = (int *)malloc(10);

    if(Pstop == NULL )
    {
        return -1;
    }

    if(myp == NULL)
        {
        return -1;
    }

    while(Pstop > pstart)
        {
        for(i = 0; i < mylen - 2; i++)
            {
            if(*Pstop >= 'A' && *Pstop <= 'F')
                {
                ant = ant + (*Pstop - 'A' + 10) * hex;
            }
            else
                {
                ant = ant + (*Pstop - '0') * hex;
                }
                Pstop --;
                hex = hex * 16;
            }
    }
    tmp = &ant;
    *Poutput = tmp;
    return 0;
}

int main()
    {
    char buf1[10];
    int  *output = NULL;
    int len = 0;
    int ret = 0;

    scanf("%s",buf1);
    len = strlen(buf1);
    ret = convert(buf1,len,&output);
    if(ret != 0)
        {
        printf("func convert() error!");
        return ret;
    }
    printf("output:%d \n",*output);

    return 0;
}



你可能感兴趣的:(C语言)