简体   繁体   English

如何在 C 中将十六进制转换为十进制?

[英]How to convert hexadecimal to decimal in C?

So, with my beginner level of experience in C I've been trying to write a code that converts hexadecimal input to a decimal with an array.因此,凭借我在 C 方面的初级经验,我一直在尝试编写一个将十六进制输入转换为带有数组的十进制的代码。 I believe you will get it more spesificly by looking at my code but it does not work properly.我相信通过查看我的代码,您会更清楚地了解它,但它不能正常工作。 I keep getting an amount that is much larger than intended.我不断收到比预期大得多的金额。

#include <stdio.h>

int main()
{


    int i, k, j, N, power, result;

    char array[50];

    result = 0;

    printf("how many charecters are there in your hexadecimal input?: \n");
    scanf("%d", &N);

    for(k=0; k<=N-1; k++)
    {
        printf("What is the %d . value of your hexadecimal input?: \n", k+1);
        scanf("%s", &array[k]);
    }


    for(i=0; i<=N-1; i++)
    {
        power = 1;
        for(j=0; j<=i; j++)
        {
        
            power = power *16;
        }
    
        if((array[i] >= 0) && (array[i] <= 9))
        {
            result = result + array[i] * power;
        
        }
    
        else
        {
            result = result + (array[i] - 'A' + 10) * power;
        }
    }   


    printf("your result is %d", result);

    return 0;
    

}

Your code is overly complicated and wrong, but the idea is correct.您的代码过于复杂和错误,但想法是正确的。

You want this:你要这个:

#include <stdio.h>
#include <string.h>

int main()
{
  char array[50];
  scanf("%49s", array);            // just use a single scanf with %s
                                   // "49s" will avoid buffer overflow of array

  int length = strlen(array);      // get length of string (and use meaningful
                                   // variable name length instead of N)    
  int result = 0;
  for (int i = 0; i < length; i++)
  {
    int nibble;                    // nibble is the hexadécimal "digit" from 0 to 15

    if ((array[i] >= '0') && (array[i] <= '9'))
    {
      nibble = array[i] - '0';
    }
    else
    {
      nibble = array[i] - 'A' + 10;
    }

    result *= 16;                  // no need to maintain power, just multiply by 16
                                   // on each run
    result += nibble;              // ... and add the nibble
  }

  printf("your result is %d", result);
  return 0;
}

There is still room for improvement:仍有改进的余地:

  • you should accept lowercase你应该接受小写
  • there is no test for invalid characters such as 'G', 'H' etc.没有针对“G”、“H”等无效字符的测试。
  • you should put the conversion code in a function such as您应该将转换代码放在 function 中,例如
    int HexStringToDecimal(const char *hexstring)
  • and certainly a bunch of other things I forgot.当然还有很多我忘记的东西。

Exercise for you: convert that code so it converts a decimal string instead of a hexadecimal string.为您练习:转换该代码,使其转换为十进制字符串而不是十六进制字符串。 Hint: the code will be simpler.提示:代码会更简单。

Side note:边注:

Avoid constructs like this:避免这样的结构:

for(k=0; k<=N-1; k++)

instead use this exact equivalent which is more readable:而是使用这个更易读的等价物:

for(k=0; k<N; k++)

just edited your code a little bit, and also the input is supposed to be from left to right instead of right to left according to which I think you have coded.只是稍微编辑了你的代码,而且输入应该是从左到右而不是从右到左,我认为你已经编码了。 Hence, for C6, first C then 6.因此,对于 C6,首先是 C,然后是 6。

#include <stdio.h>

int main()
{


    int i, k, j, N, power, result;

    char array[50];

    result = 0;

    printf("how many charecters are there in your hexadecimal input?: \n");
    scanf("%d", &N);

    for(k=0; k<=N-1; k++)
    {
        printf("What is the %d . value of your hexadecimal input?: \n", k+1);
        scanf(" %c", &array[k]);
    }


    for(i=0; i<=N-1; i++)
    {
        power = 1;
        
        for(j=0; j<=N-2-i; j++)
        {
            power = power*16;
        }
        
        if((array[i] >= '0') && (array[i] <= '9'))
        {
            result = result + (array[i] - '0') * power;
        
        }
    
        else
        {
            result = result + (array[i] - 'A' + 10) * power;
        }
    }   


    printf("your result is %d", result);

    return 0;
    
}

the takeaways外卖

  1. your input taking is inefficeient.您的输入效率低下。 and in that too %c instead of %s in scanf.并且在 scanf 中也是 %c 而不是 %s。
  2. if((array[i] >= 0) && (array[i] <= 9)) , suppose i=1 and array[1] = 7. Now, you are comparing ascii value of 7 which is 55, instead of 7. if((array[i] >= 0) && (array[i] <= 9)) ,假设 i=1 和 array[1] = 7。现在,您正在比较 7 的 ascii 值,即 55,而不是7.
  3. same thing in the statement of if, the ascii values of array[i] are being used so I have subtracted accordingly.在 if 的语句中同样的事情,正在使用 array[i] 的 ascii 值,所以我相应地减去了。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM