3

我正在尝试htoi(char*)K&R 的 The C Programming Language 中的函数(练习 2-3,第 43 页)。

该函数旨在将十六进制字符串转换为基数 10。

我相信我有它的工作。这是我的代码:

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

enum {hexbase = 16};
typedef enum{false, true} bool;

unsigned int htoi(char* s);
bool hasHexPrefix(char* s);

int main(int argc, char** argv) {   

    if(argc <= 1) {
        printf("Error: Not enough arguments.\n");
        return EXIT_FAILURE;
    }else {
        for(int i = 1; i < argc; i++) {
            unsigned int numericVal = htoi(argv[i]);
            printf("%s => %u\n",argv[i],numericVal);
        }
    }
}

unsigned int htoi(char* s) {
    unsigned int output = 0;
    unsigned int len = (unsigned int)(strlen(s));

    unsigned short int firstIndex = hasHexPrefix(s) ? 2 : 0;

    /* start from the end of the str (least significant digit) and move to front */
    for(int i = len-1; i >= firstIndex; i--) {
        int currentChar = s[i];
        unsigned int correspondingNumericVal = 0;
        if(currentChar >= '0' && currentChar <= '9') {
            correspondingNumericVal = currentChar - '0';
        }else if(currentChar >= 'a' && currentChar <= 'f') {
            correspondingNumericVal = (currentChar - 'a') + 10;
        }else if(currentChar >= 'A' && currentChar <= 'F') {
            correspondingNumericVal = (currentChar - 'A') + 10;
        }else {
            printf("Error. Invalid hex digit: %c.\n",currentChar);
        }
        /* 16^(digitNumber) */
        correspondingNumericVal *= pow(hexbase,(len-1)-i);
        output += correspondingNumericVal;
    }

    return output;
}

bool hasHexPrefix(char* s) {
    if(s[0] == '0')
        if(s[1] == 'x' || s[1] == 'X')
            return true;

    return false;
}

我的问题是htoi(char*)函数中的以下行:

unsigned short int firstIndex = hasHexPrefix(s) ? 2 : 0;

当我删除shortmakefirstIndex变成一个unsigned int而不是一个unsigned short int,我得到一个无限循环。

因此,当我从 in 后面开始时shtoi(char* s)永远i >= firstIndex不会评估为假。

为什么会这样?我是否遗漏了一些微不足道的事情,或者我做了一些非常错误的事情来导致这种未定义的行为?

4

1 回答 1

4

由于通常的算术转换,当firstIndexis unsigned int, in i >= firstIndextheni被转换为。unsigned int所以如果i是负数,它在比较表达式中变成一个大整数。当in 时firstIndex,提升为并比较两个有符号整数。unsigned short inti >= firstIndexfirstIndexint

你可以改变:

for(int i = len-1; i >= firstIndex; i--)

for(int i = len-1; i >= (int) firstIndex; i--)

在两种情况下都具有相同的行为。

于 2015-03-08T20:47:08.883 回答