将十六进制转换为int的C代码 [英] C code to convert hex to int

查看:102
本文介绍了将十六进制转换为int的C代码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写此代码,以将十六进制条目转换为其等效的整数。因此,A将为10,B将为11,依此类推。这段代码的行为很奇怪,因为它是段。随机位置的错误,有时包括一个额外的换行符,将使其正常工作。我正在尝试调试它,以便我可以了解我在这里做错了什么。有人可以看一下在这里帮助我吗?非常感谢您的宝贵时间。

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


            }


推荐答案

我们来看一下。

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 从未分配任何其他值。通常,您会执行以下操作:

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;

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

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

然后,查看 main

main()
{

根据隐式int规则通常是不良做法,至少是IMO。最好指定返回类型。

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

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

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

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

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

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

这篇关于将十六进制转换为int的C代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆