atoi 和 htoi的实现

#include <stdio.h>

#define DEC 10
#define HEX 16

int atoi(const char[]);

int htoi(const char[]);

int main(int argc, char **argv) {
    const char a[] = "5";
    const char b[] = "18";
    const char c[] = "255";

    const char m[] = "a";
    const char n[] = "3f";
    const char q[] = "15f";

    printf ("Value 1: %d\n", atoi(a));
    printf ("Value 2: %d\n", atoi(b));
    printf ("Value 3: %d\n", atoi(c));

    printf ("Value 4: %d\n", htoi(m));
    printf ("Value 5: %d\n", htoi(n));
    printf ("Value 6: %d\n", htoi(q));

    return 0;
}

int atoi(const char s[]) {
    int value = 0;
    for (int i = 0; s[i] != '\0'; ++i) {
        if ('0' <= s[i] && s[i] <= '9') {
            value = value * DEC + (s[i] - '0');
        } else {
            value = 0;
        }
    }

    return value;
}

int htoi(const char s[]) {
    int value = 0;
    for (int i = 0; s[i] != '\0'; ++i) {
        if ('0' <= s[i] && s[i] <= '9') {
            value = value * HEX + (s[i] - '0');
        } else if ('a' <= s[i] && s[i] <= 'f') {
            value = value * HEX + (s[i] - 'a' + DEC);
        } else if ('A' <= s[i] && s[i] <= 'F') {
            value = value * HEX + (s[i] - 'A' + DEC);
        } else {
            value = 0;
        }
    }

    return value;
}
©️2020 CSDN 皮肤主题: 技术黑板 设计师:CSDN官方博客 返回首页