【发布时间】: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 并查看我哪里出错了。我不想使用标准库。谢谢