简体   繁体   中英

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. 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.
  • you should put the conversion code in a function such as
    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.

#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.
  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.
  3. same thing in the statement of if, the ascii values of array[i] are being used so I have subtracted accordingly.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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