Why do we use n = 16 * n + hexdigit

本文深入探讨了将十六进制字符串转换为整数值的算法原理,解释了公式 'n = 16 * n + hexdigit' 的含义及背后的数学逻辑,并通过实例展示了如何使用此算法进行转换。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

我的主力博客:半亩方塘

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.


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值