/* hexadecimal to decimal conversion */
#include <stdio.h>
#include <math.h>
#include <string.h>
int main()
{
char hex[17];
long long decimal;
int i , val, len;
decimal = 0;
// Input hexadecimal number from user
printf("Enter any hexadecimal number: ");
gets(hex);
//Find the length of total number of hex digit
len = strlen(hex);
len--;
for(i=0; hex[i]!='\0'; i++)
{
// Find the decimal representation of hex[i]
if(hex[i]>='0' && hex[i]<='9')
{
val = hex[i] - 48;
}
else if(hex[i]>='a' && hex[i]<='f')
{
val = hex[i] - 97 + 10;
}
else if(hex[i]>='A' && hex[i]<='F')
{
val = hex[i] - 65 + 10;
}
decimal += val * pow(16, len);
len--;
}
printf("Hexadecimal number = %s\n", hex);
printf("Decimal number = %lld", decimal);
return 0;
}
在上面的程序中,当我使用 scanf 而不是 gets 时,它没有给出结果。为什么?我使用了 scanf("%x",hex);
。请解释一下 decimal += val * pow(16, len);
。提前非常感谢。
最佳答案
因为如果您使用 scanf()
,它会为您完成字符串转换,这就是它的全部要点。
unsigned int x;
if(scanf("%x", &x) == 1)
printf("you entered %d (hex 0x%x)\n", x, x);
您不能将 %x
指针组合到字符数组,它需要一个指向无符号整数的指针。这当然在 manual page 中有详细记录。
此外,在这里使用 pow()
似乎有点多余,只需将您所拥有的值乘以 16然后添加每个新数字即可:
unsigned int parsehex(const char *s)
{
unsigned int x = 0;
const char *digits = "0123456789abcdef";
const char *p;
while(*s && (p = strchr(digits, tolower(*s++))) != NULL)
{
x *= 16;
x += (unsigned int) (p - digits);
}
return x;
}
这比您的代码“重”一点(使用 strchr()
),但更短,因此可能更容易验证。如果它对性能过于关键,我会考虑研究它。
关于C:使用 scanf() 函数而不是 gets,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43003074/