Convert a character digit to the corresponding integer in C

Flow picture Flow · Mar 10, 2009 · Viewed 507.6k times · Source

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

For example, from '5' to 5?

Answer

Chris Young picture Chris Young · Mar 10, 2009

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.