Convert a character digit to the corresponding integer in C

CType Conversion

C Problem Overview


Is there a way to convert a character to an integer in C?

For example, from '5' to 5?

C Solutions


Solution 1 - C

As per other replies, this is fine:

char c = '5';
int x = c - '0';

Also, for error checking, you may wish to check isdigit(c) is true first. Note that you cannot completely portably do the same for letters, for example:

char c = 'b';
int x = c - 'a'; // x is now not necessarily 1

The standard guarantees that the char values for the digits '0' to '9' are contiguous, but makes no guarantees for other characters like letters of the alphabet.

Solution 2 - C

Subtract '0' like this:

int i = c - '0';

The C Standard guarantees each digit in the range '0'..'9' is one greater than its previous digit (in section 5.2.1/3 of the C99 draft). The same counts for C++.

Solution 3 - C

If, by some crazy coincidence, you want to convert a string of characters to an integer, you can do that too!

char *num = "1024";
int val = atoi(num); // atoi = ASCII TO Int

val is now 1024. Apparently atoi() is fine, and what I said about it earlier only applies to me (on OS X (maybe (insert Lisp joke here))). I have heard it is a macro that maps roughly to the next example, which uses strtol(), a more general-purpose function, to do the conversion instead:

char *num = "1024";
int val = (int)strtol(num, (char **)NULL, 10); // strtol = STRing TO Long

strtol() works like this:

long strtol(const char *str, char **endptr, int base);

It converts *str to a long, treating it as if it were a base base number. If **endptr isn't null, it holds the first non-digit character strtol() found (but who cares about that).

Solution 4 - C

To convert character digit to corresponding integer. Do as shown below:

char c = '8';                    
int i = c - '0';

Logic behind the calculation above is to play with ASCII values. ASCII value of character 8 is 56, ASCII value of character 0 is 48. ASCII value of integer 8 is 8.

If we subtract two characters, subtraction will happen between ASCII of characters.

int i = 56 - 48;   
i = 8;

Solution 5 - C

Subtract char '0' or int 48 like this:

char c = '5';
int i = c - '0';

Explanation: Internally it works with ASCII value. From the ASCII table, decimal value of character 5 is 53 and 0 is 48. So 53 - 48 = 5

OR

char c = '5';
int i = c - 48; // Because decimal value of char '0' is 48

That means if you deduct 48 from any numeral character, it will convert integer automatically.

Solution 6 - C

char numeralChar = '4';
int numeral = (int) (numeralChar - '0');

Solution 7 - C

Here are helper functions which allow to convert digit in char to int and vice versa:

int toInt(char c) {
    return c - '0';
}

char toChar(int i) {
    return i + '0';
}

Solution 8 - C

Just use the atol()function:

#include <stdio.h>
#include <stdlib.h>

int main() 
{
    const char *c = "5";
    int d = atol(c);
    printf("%d\n", d);

}

Solution 9 - C

If it's just a single character 0-9 in ASCII, then subtracting the the value of the ASCII zero character from ASCII value should work fine.

If you want to convert larger numbers then the following will do:

char *string = "24";

int value;

int assigned = sscanf(string, "%d", &value);

** don't forget to check the status (which should be 1 if it worked in the above case).

Paul.

Solution 10 - C

char chVal = '5';
char chIndex;

if ((chVal >= '0') && (chVal <= '9')) {

    chIndex = chVal - '0';
}
else 
if ((chVal >= 'a') && (chVal <= 'z')) {

    chIndex = chVal - 'a';
}
else 
if ((chVal >= 'A') && (chVal <= 'Z')) {

    chIndex = chVal - 'A';
}
else {
    chIndex = -1; // Error value !!!
}

Solution 11 - C

When I need to do something like this I prebake an array with the values I want.

const static int lookup[256] = { -1, ..., 0,1,2,3,4,5,6,7,8,9, .... };

Then the conversion is easy

int digit_to_int( unsigned char c ) { return lookup[ static_cast<int>(c) ]; }

This is basically the approach taken by many implementations of the ctype library. You can trivially adapt this to work with hex digits too.

Solution 12 - C

Check this,

char s='A';

int i = (s<='9')?(s-'0'):(s<='F')?((s-'A')+10):((s-'a')+10);

for only 0,1,2,....,E,F.

Solution 13 - C

If your digit is, say, '5', in ASCII it is represented as the binary number 0011 0101 (53). Every digit has the highest four bits 0011 and the lowest 4 bits represent the digit in bcd. So you just do

char cdig = '5';
int dig = cdig & 0xf; // dig contains the number 5

to get the lowest 4 bits, or, what its same, the digit. In asm, it uses and operation instead of sub(as in the other answers).

Solution 14 - C

You would cast it to an int (or float or double or what ever else you want to do with it) and store it in anoter variable.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionFlowView Question on Stackoverflow
Solution 1 - CChris YoungView Answer on Stackoverflow
Solution 2 - CJohannes Schaub - litbView Answer on Stackoverflow
Solution 3 - CChris LutzView Answer on Stackoverflow
Solution 4 - CAshishView Answer on Stackoverflow
Solution 5 - CArifView Answer on Stackoverflow
Solution 6 - CeaseoutView Answer on Stackoverflow
Solution 7 - CMaxim MakhunView Answer on Stackoverflow
Solution 8 - CDylan hallsView Answer on Stackoverflow
Solution 9 - CPaul W HomerView Answer on Stackoverflow
Solution 10 - CAlphaneoView Answer on Stackoverflow
Solution 11 - CMichael AndersonView Answer on Stackoverflow
Solution 12 - CShivaView Answer on Stackoverflow
Solution 13 - CGarmekainView Answer on Stackoverflow
Solution 14 - CSeanJAView Answer on Stackoverflow