我编写的程序在只包含单个十六进制值的人口统计中工作。(可能不是最优雅的解决方案,但我是一个新程序员)我的问题是,我该如何处理多个十六进制数字,如0xAF或0xFF等?我不是很确定,而且在尝试的过程中,我似乎把自己搞糊涂了。我并不是要求有人拉着我的手,而是给我一个提示,告诉我在这段代码中我哪里出了问题,以及如何修复它。
谢谢:)
/* Exercise 2-3. Write the function htoi(s), which converts a string of
* hexadecimal digits (including an optional 0x or 0X) into it's equivalent
* integer value. The allowable digits are 0...9 - A...F and a...f.
*
*/
#include <stdio.h>
#include <string.h>
#define NL '\n'
#define MAX 24
int htoi(char *hexd);
int
main(void)
{
char str[MAX] = {0};
char hex[] = "0123456789ABCDEFabcdef\0";
int c;
int i;
int x = 0;
while((c = getchar()) != EOF) {
for(i = 0; hex[i] != '\0'; i++) {
if(c == hex[i])
str[x++] = c;
}
if(c == NL) {
printf("%d\n", htoi(str));
x = 0, i = x;
}
}
return 0;
}
int
htoi(char *hexd)
{
int i;
int n = 0;
for(i = 0; isdigit(hexd[i]); i++)
n = (16 * i) + (hexd[i] - '0');
for(i = 0; isupper(hexd[i]); i++) /* Let's just deal with lowercase characters */
hexd[i] = hexd[i] + 'a' - 'A';
for(i = 0; islower(hexd[i]); i++) {
hexd[i] = hexd[i] - 'a';
n = (16 + i) + hexd[i] + 10;
n = hexd[i] + 10;
}
return n;
}发布于 2009-04-30 01:48:29
已经有人问过这个问题(十六进制到int,k&r 2.3)。看一看,有很多好的答案,但你必须填补空白。
Hex to Decimal conversion [K&R exercise]
编辑:
在……里面
char hex[] = "0123456789ABCDEFabcdef\0";\0不是必需的。十六进制已终止为nul。len (0...f) +1= 17字节长。
发布于 2009-04-30 06:25:08
我将选择一个循环,并让您重新考虑您的实现。具体地说:
for(i = 0; isdigit(hexd[i]); i++)
n = (16 * i) + (hexd[i] - '0');不会像你想的那样...
isdigit()为TRUE的第一个字符。isdigit()为FALSE的第一个字符上停止。isdigit('\0')为FALSE。不过,我担心这可能是偶然正确的。整个程序需要考虑的事情:
htoi("1234")的用户正在调用未定义的行为。你真的不想这样做,只有一个遍历数字的循环会处理非零位数的数字,如果我向stdin0123456789ABCDEF0123456789ABCDEF,会发生什么,你希望在80000000中得到吗?,,,
,
0123456789ABCDEF0123456789ABCDEF,,
80000000中得到的是什么?你得到了什么?你是我不会使用NL surprised?'\n'。C语言的使用很可能会在宏不方便使用的很多上下文中看到\n,所以最好现在就习惯它……发布于 2013-08-17 11:34:26
我认为字符串的最大长度应该是10或18,而不是24。(如果您已经检查了机器上的int并遵循了下面的推理,那么将其作为注释包含在您的代码中将是有益的。)
10 :由于htoi()返回一个int,int通常是4个字节(也请检查您的系统),因此十六进制数的长度最多为8位(4位到1位十六进制数字,8位到一个字节),我们希望允许可选的0x或0X。
18 :如果htoi()返回一个long及其8个字节会更好(同样,请检查您的系统),这样十六进制数的长度最多为16位,并且我们希望允许可选的0x或0X。
请注意,int和long的大小与机器相关,请查看K&R书中的练习2.1以找到它们。
https://stackoverflow.com/questions/805049
复制相似问题