【问题标题】:C code to convert hex to int将十六进制转换为整数的C代码
【发布时间】:2011-02-09 23:15:13
【问题描述】:

我正在编写此代码以将十六进制条目转换为其等效整数。所以 A 是 10,B 是 11 等等。这段代码的行为很奇怪,因为它是分段的。随机位置的故障并有时包含一个额外的换行符将使其工作。我正在尝试调试它,这样我才能理解我在这里做错了什么。任何人都可以在这里看看并帮助我吗?非常感谢您的时间。

/* 为感兴趣的人修复了工作代码 */

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


            unsigned int hextoint(const char temp[])
            {

            int i;
            int answer = 0;
            int dec;
            char hexchar[] = "aAbBcCdDeEfF" ;


            for ( i=0; temp[i] != '\0'; i++ )
            {

                if ( temp[i] == '\0')
                {

                    return ;        
                }

                if (temp[i] == '0' || temp[i] == 'x' || temp[i] == 'X' )
                {       
                    printf("0");
                    answer = temp[i];
                }

                // compare each temp[i] with all contents in hexchar[]
                int j;
                int a = temp[i];
                for ( j=0; hexchar[j] != '\0'; j++)
                {
                    if ( temp[i] == hexchar[j] )
                    {
                    answer *= 16;
                    answer = answer + 10 + (j/2);
  //                    printf("%d\n",answer );
                    break;      
                    }
                }

            }

            return answer;  

            }


            main()
            {
            char *test[] = 
            {   "bad",
                "aabbdd"
                "0100",
                "0x1",
                "0XA",
                "0X0C0BE",
                "abcdef",
                "123456",
                "0x123456",
                "deadbeef", 
                "zog_c"
            };

            int answer=0;

            // Calculate the number of char's.
            int numberOfChars;
            numberOfChars = sizeof test /sizeof test[0];

            printf("main():Number of chars = %d\n",numberOfChars);
            int i;
            // Go through each character and convert Hex to Integers.
            for ( i = 0; i<numberOfChars;i++)
            {
                // Need to take the first char and then go through it and convert            
                                        it.
                answer = hextoint(test[i]);
                printf("%d\n",answer ); 
            }


            }

【问题讨论】:

  • 您是否尝试过使用调试器一次执行一行,以查看行为与您的预期不同的地方?
  • 如果这是您需要的其他功能(而不仅仅是编写十六进制到整数转换器的练习),请查看标准库中的 strtol 函数。
  • sizeof(test) 和 sizeof(test[0]) 具有相同的大小。他们都是指针
  • 奥利,我有。 gdb 说它在 for ( i=0; temp[i] != '\0'; i++ ) 处崩溃,因为内存超出范围。但是我发现这种行为很奇怪,并且无法弄清楚为什么 mem.超出范围。
  • Phil,我正在尝试调试它以更好地理解 C 并查看我哪里出错了。我不想使用标准库。谢谢

标签: c arrays hex


【解决方案1】:

让我们来看看。

unsigned int hextoint(const char temp[])
{
    int i;
    int answer = 0;
    char hexchar[] = "aAbBcCdDeEfF" ;

    for ( i=0; temp[i] != '\0'; i++ )
    {
        printf("In here");
        printf("%c\t",temp[i] );
    }

    return answer;  
}

这似乎甚至没有尝试进行任何转换。它应该始终返回 0,因为从未为 answer 分配任何其他值。通常,您会执行以下操作:

for (i=0; input[i] != '\0'; i++) {
    answer *= 16;
    answer += digit_value(input[i]);
}
return answer;

digit_value(显然足够)返回单个数字的值。一种方法是:

int digit_value(char input) { 
    input = tolower(input);
    if (input >= '0' && input <= '9')
        return input - '0';
    if (input >= 'a' && input <= 'f')
        return input - 'a' + 10;
    return -1; // signal error.
}

然后,看着main

main()
{

依赖于“隐式 int”规则通常是不好的做法,至少 IMO 是这样。最好指定返回类型。

// Calculate the number of char's.
int numberOfChars;
numberOfChars = sizeof test /sizeof test[0];

这实际上计算的是字符串的数量,而不是chars 的数量。

for ( i = 0; i<=numberOfChars;i++)

有效下标从 0 到项目数 - 1,因此这会尝试读取数组末尾(给出未定义的行为)。

【讨论】:

  • 你还需要检查AF
  • @Peyman:更仔细地阅读代码。如果您放弃,请搜索“tolower”...
  • 感谢大家的大力帮助。正如你们所指出的,sizeof 计算是问题所在。
【解决方案2】:

这适用于 unsigned int 范围内的任何数字,好处是它不使用任何其他库函数,因此非常适合空间紧张的微控制器。

unsigned int hexToInt(const char *hex)
  {
    unsigned int result = 0;

    while (*hex)
      {
        if (*hex > 47 && *hex < 58)
          result += (*hex - 48);
        else if (*hex > 64 && *hex < 71)
          result += (*hex - 55);
        else if (*hex > 96 && *hex < 103)
          result += (*hex - 87);

        if (*++hex)
          result <<= 4;
      }

    return result;
  }

【讨论】:

    【解决方案3】:

    问题在于计算numberOfChars 部分。 sizeof test 实际上是指针的大小,而不是数组中所有字符的总长度,因此代码中返回的数字将为 1,这使得 for 循环转到测试的第二个索引 (test[1])最后没有\0。尝试使用strlen 计算numberOfChars

    【讨论】:

    • 由于test 被定义为一个指针数组,sizeof test 产生数组中的字节数。 sizeof(test[0]) 产生数组中单个指针的大小。除法给出指针的数量。
    【解决方案4】:

    这可能不是我认为的最佳方法,但它应该可以正常工作。

    unsigned int hex_to_int(const char* hex) {
        unsigned int result = 0;
        size_t len = strlen(hex);
        for (size_t i = 0; i < len; ++i) {
            char cur_char = tolower(hex[len - i - 1]);
            // direct return if encounter any non-hex character.
            if (!(isdigit(cur_char) && (cur_char >= 'a' && cur_char <= 'f'));) 
                return result;
    
            unsigned int char_val = (isdigit(cur_char) ? cur_char - '0' : 10 + cur_char - 'a');
            result += round(pow(16, i)) * char_val;
        }
        return result;
    }
    

    【讨论】:

      猜你喜欢
      • 2010-10-16
      • 2011-08-11
      • 2019-01-01
      • 2014-04-16
      • 1970-01-01
      • 2017-08-12
      • 2016-12-04
      相关资源
      最近更新 更多