Yahoo Answers is shutting down on May 4th, 2021 (Eastern Time) and beginning April 20th, 2021 (Eastern Time) the Yahoo Answers website will be in read-only mode. There will be no changes to other Yahoo properties or services, or your Yahoo account. You can find more information about the Yahoo Answers shutdown and how to download your data on this help page.

How do you convert char numbers to int numbers in C++?

So I have a char array of values with a size of 10. Like this:

char a[0,0,0,0,0,0,1,E,4,5]

How do I convert these char values to their equivalent number value. It is base 16, so the E would be equal to 14.

3 Answers

Relevance
  • ?
    Lv 6
    9 years ago
    Favorite Answer

    Two ways you could do it:

    1)

    include <stdlib.h>

    use the function strtol to convert strings to longs

    long int strtol ( char * input, char* endOfNumber, int base)

    Unfortunately this works on strings not chars so what you'd need to so is something like:

    char myString[2];

    long values[10];

    myString[1] = 0;

    for (int i = 0; i<10; i++) {

    myString[0] = a[i];

    values[i] = strtol(myString, NULL, 16);

    }

    The alternative method is to make your own function based on the ascii values of the char:

    int hexCharToInt(char* input) {

    if ((*input >=48) && (*input <= 57)) // 0 to 9

    return (*input - 48);

    if ((*input >= 65) && (*input <= 70)) // A to F

    return (*input - 55);

    if ((*input >= 97) && (*input <= 102)) // a to f

    return (*input - 87);

    return -1;

    }

    your code then becomes:

    int values[10];

    for (int i = 0; i<10; i++) {

    values[i] = hexCharToInt(a[i]);

    }

  • 5 years ago

    each and every char has a particular integer value assigned to it. examine the ASCII tables in case you pick for to correctly known. To get that integer value, all you do is solid the char to an int. To get it so the char A could be 0, only subtract int value for 'A' out of your char. So 'A' - 'A' = 0, 'B' - 'A' = a million, and so on. So working example: char c = 'B'; int i = (int)c - (int)'A'; printf("%i", i); //you need to get a million. easily, i found out you do no longer might desire to casting. The compiler does that for you.

  • 9 years ago

    int array[9];

    for (int i=0;i<9;i++)

    {

    array[i]=a[i];

    }

    for (int i=0;i<9;i++)

    {

    cout<<hex<<array[i];

    }

Still have questions? Get your answers by asking now.