将十六进制转换为整数的C代码

发布于 2024-10-16 20:26:36 字数 2348 浏览 3 评论 0原文

我正在编写这段代码来将十六进制条目转换为其等效的整数。所以 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 ); 
            }


            }

I am writing this code to convert a hex entry into its integer equivalent. So A would be 10 and B would be 11 etc. This code acts weirdly, in that it seg. faults at random locations and including an extra newline character at times will get it to work. I am trying to debug it, just so I can understand what I am doing wrong here. Can anyone take a look and help me here ? Thanks a lot for your time.

/* Fixed working code for anyone interested */

         #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 ); 
            }


            }

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

開玄 2024-10-23 20:26:36

我们来看一下。

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”规则通常是不好的做法,至少在我看来是这样。最好指定返回类型。

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

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

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

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

Let's take a look.

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;  
}

This doesn't seem to even try to do any conversion. It should always return 0, since answer is never assigned any other value. Normally, you'd do something like:

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

Where digit_value (obviously enough) returns the value of an individual digit. One way to do this is:

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.
}

Then, looking at main:

main()
{

Depending on the "implicit int" rule is generally poor practice, at least IMO. It's much better to specify the return type.

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

This actually calculates the number of strings, not the number of chars.

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

Valid subscripts run from 0 through the number of items - 1, so this attempts to read past the end of the array (giving undefined behavior).

白云不回头 2024-10-23 20:26:36

这适用于 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;
  }

This'll work for any number within the unsigned int range, the nice thing is it does not use any other library functions so it is great for micro-controllers where space is tight.

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;
  }
丑疤怪 2024-10-23 20:26:36

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

The problem is with calculating numberOfChars part. sizeof test is actually the size of the pointer, not the total length of all characters in your array, so the number returned in your code would be 1, which makes the for loop go to the second index of test (test[1]) which does not have a \0 at the end. Try using strlen for calculating numberOfChars.

很酷不放纵 2024-10-23 20:26:36

这可能不是我最好的方法,但它应该没有问题。

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;
}

This may not me the most optimal method, but it should work without problem.

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;
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文