码迷,mamicode.com
首页 > 其他好文 > 详细

Why do we use n = 16 * n + hexdigit

时间:2015-03-28 17:19:59      阅读:269      评论:0      收藏:0      [点我收藏+]

标签:c   数制转换   

Go to my personal blog

There is a program to convert a string of hexadecimal digits into its equivalent integer value as below.

enum loop {NO, YES};

/* htoi: convert hexadecimal string s to integer */
int htoi(char s[])
{
    int hexdigit, i, n;
    enum loop inhex;

    i = 0;
    if (s[i] == '0') {     /* skip optional 0x or 0X */
        ++i;
        if (s[i] == 'x' || s[i] == 'X')
            ++i;
    }
    n = 0;              /* integer value to be returned */
    inhex = YES;        /* assume valid hexadecimal digit */
    for ( ; inhex = YES; ++i) {
        if (s[i] >= '0' && s[i] <= '9')
            hexdigit = s[i] - '0';
        else if (s[i] >= 'a' && s[i] <= 'f')
            hexdigit = s[i] - 'a' + 10;
        else if (s[i] >= 'A' && s[i] <= 'F')
            hexdigit = s[i] - 'A' + 10;
        else
            inhex = NO;
        if (inhex == YES)
            n = 16 * n + hexdigit;
    }
    return n;
}  


Why do we use ‘n = 16 * n + hexdigit‘ to compute the value ? The figure below gives the reason.

技术分享


Similarly, we can use n = 8 * n + octdigit to convert octal string, we can use n = 2 * n + bindigit to convert binary string, too.

A program to convert hexadecimal string.


Why do we use n = 16 * n + hexdigit

标签:c   数制转换   

原文地址:http://blog.csdn.net/abnerwang2014/article/details/44702611

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!