编写函数htio(s),把由16进制数字组成的字符串转换为与之等价的整数值

/**************************************************************************
    类型:<c程序设计语言(第二版.新版)> 练习 2-3
    名称:lx.c
    author: wubenzhimu
    data:   2012.11.16
    功能:编写函数htio(s),把由16进制数字组成的字符串(包含可选的前缀0x或0X)
    转换为与之等价的整数值。字符串中可以包含的数字包括:0-9,a-f,A-F。
***************************************************************************/


#include <stdio.h>
#include <stdlib.h>

unsigned int htoi(const char s[]);
int hexalpha_to_int(int c);

int main(void)
{
    /* 定义指针 */
    char *endp = NULL;
    char *test[] =
    {
        "F00",
        "bar",
        "0100",
        "0x1",
        "0XA",
        "0X0c0BE",
        "abcdef",
        "123456",
        "0x123456",
        "deadbeef",
        "zog_c"
    };

    unsigned int result;
    unsigned int check;
    
    /**
    * size_t 是c内部预定义的一个类型 
    * size_t numtests == unsigned int numtests
    * 确定数组的个数
    */
    size_t numtests = sizeof test / sizeof test[0];

    size_t thistest;

    for(thistest = 0; thistest < numtests; thistest++)
    {
        result = htoi(test[thistest]);
        /**
        * unsigned long int strtoul(const char *nptr,char *endptr,int base);
        *(将字符串转换成无符号长整型数)
        */
        check = (unsigned int)strtoul(test[thistest], &endp, 16);

        if((*endp != '\0' || result == check) && result != 0)
        {
            printf("测试(Testing) %s. 正确(Correct). %u\n", test[thistest], result);
        }
        else
        {
            printf("测试(Testing) %s. 错误(Incorrect). %u\n", test[thistest], result);
        }
    }

    return 0;
}

/**
* 十进制转换二进制
* 方法 第一位值*16的0次方,第二次值*16的1次方。。。。所有的值相加,就是十进制的数
*/
unsigned int htoi(const char s[])
{
    unsigned int answer = 0;
    int i = 0;
    int valid = 1;
    int hexit;
    
    /** 
    * 十六进制: 0x 或者 0X 开头
    * 这里判断 char s[] 是否为16进制
    */
    if(s[i] == '0')
    {
        ++i;
        if(s[i] == 'x' || s[i] == 'X')
        {
            ++i;
        }
    }
    
    while(valid && s[i] != '\0')
    {
        answer = answer * 16;
        if(s[i] >= '0' && s[i] <= '9')
        {
            answer = answer + (s[i] - '0');
        }
        else
        {
            hexit = hexalpha_to_int(s[i]);
            if(hexit == 0)
            {
                valid = 0;
            }
            else
            {
                answer = answer + hexit;
            }
        }
        ++i;
    }
    
    if(!valid)
    {
        answer = 0;
    }

    return answer;
}

/**
*    功能实现:十六进制字符 包含在 a-f 或 A-F 中 启用这个方法 
*/
int hexalpha_to_int(int c)
{
    char hexalpha[] = "aAbBcCdDeEfF";
    int i;
    int answer = 0;

    for(i = 0; answer == 0 && hexalpha[i] != '\0'; i++)
    {
        if(hexalpha[i] == c)
        {
            answer = 10 + (i / 2);
        }
    }

    return answer;
}

超的程序,自己写还是有点问题滴。。程序局部有改动

结果:

posted @ 2012-11-16 21:52  无本之木a  阅读(2716)  评论(0编辑  收藏  举报