这适用于C编程。我正在中期学习,练习测试中的一个问题让我有些困惑,并希望有人可以帮助我完成代码。
该功能的代码是:
int xtoi(char s[])
{
int i;
int result;
i = result = 0;
while (s[i]) {
if (s[i] >= '0' && s[i] <= '9') {
result = result * 16 + s[i++] - '0';
} else if (s[i >= 'a' && s[i] <= 'f') {
result = result * 16 + s[i++] - 'a' + 10;
} else if (s[i] >= 'A' && s[i] <= 'F') {
result = result * 16 + s[i++] - 'A' +10;
}
}
return result;
}
以下结果是什么?
xtoi("1fa")
答案应该是506
,但我不知道如何。它可能很简单,但这对我来说都是相对较新的,所以非常感谢任何帮助和指导。
提前致谢。
答案 0 :(得分:0)
该函数将十六进制字符串转换为int
s。这与atoi
类似。
int xtoi(char s[])
{
int i = 0;
int result = 0;
/* while we haven't seen the null terminator */
while (s[i]) {
/* if this char is a digit
* convert this char to an int and then add
* it to the next decimal place in the number.
* Then advance to the next character */
if (s[i] >= '0' && s[i] <= '9')
result = result * 16 + s[i++] - '0';
/* if this character is a hex digit
* convert this char to an int and then add
* it to the next decimal place in the number.
* Then advance to the next character */
else if (s[i] >= 'a' && s[i] <= 'f')
result = result * 16 + s[i++] - 'a' + 10;
/* same as above, except for uppercase hex digits */
else if (s[i] >= 'A' && s[i] <= 'F')
result = result * 16 + s[i++] - 'A' + 10;
}
/* return the converted number */
return result;
}
这个程序可以像这样重写
int xtoi(char s[])
{
int i = 0;
int result = 0;
/* while we haven't seen the null terminator */
for (i = 0; s[i]; ++i) {
/* if this char is a digit
* convert this char to an int and then add
* it to the next decimal place in the number. */
if (isdigit(s[i]))
result = result * 16 + (s[i] - '0');
/* if this character is a hex digit
* convert this char to an int and then add
* it to the next decimal place in the number. */
else if (isxdigit(s[i])) {
/* if the hex digit is uppercase, the char to subtract
* from is also uppercase. Otherwise it is lowercase */
char base = isupper(s[i]) ? 'A' : 'a';
result = result * 16 + s[i] - base + 10;
}
}
/* return the converted number */
return result;
}
新xtoi("1fa");
的输出是正确的:506。
答案 1 :(得分:0)
s[i]
是来自&#39; 0&#39;的char
到&#39; 9&#39;,将其转换为
对应的int
(0到9)。s[i]
是char
来自&#39; a&#39;到&#39; f&#39;,将其转换为相应的int
(10到16)。s[i]
是char
来自&#39; A&#39;到&#39; F&#39;,将其转换为相应的int
(10到16)。然后将所有这些数字相加(遵循规则)以生成由s
表示的十六进制值。
有关规则的提示:例如,假设您想要获得一个十进制数字,包括&#39; 4&#39;和&#39; 2&#39;。您首先将临时结果设为4,将其乘以10,并将该结果加2。这将给你你想要的:4 * 10 + 2 = 42。
请再考虑一下,我保证你可以自己理解它。
顺便说一句,xtoi("1fa")
的结果与strtol("1fa", NULL, 16)