Leif Ericson - 1 year ago 117
C Question

# Char to int conversion in C

If I want to convert a single numeric

`char`
to it's numeric value, for example, if:

``````char c = '5';
``````

and I want
`c`
to hold
`5`
`'5'`
, is it 100% portable doing it like this?

``````c = c - '0';
``````

I heard that all character sets store the numbers in consecutive order so I assume so, but I'd like to know if there is an organized library function to do this conversion, and how it is done conventionally. I'm a real beginner :)

Yes, this is a safe conversion. C requires it to work. This guarantee is in section 5.2.1 paragraph 2 of the latest ISO C standard, a recent draft of which is N1570:

Both the basic source and basic execution character sets shall have the following members:
[...]
the 10 decimal digits
`0 1 2 3 4 5 6 7 8 9`
[...]
In both the source and execution basic character sets, the value of each character after 0 in the above list of decimal digits shall be one greater than the value of the previous.

Both ASCII and EBCDIC, and character sets derived from them, satisfy this requirement, which is why the C standard was able to impose it. Note that letters are not contiguous iN EBCDIC, and C doesn't require them to be.

There is no library function to do it for a single `char`, you would need to build a string first:

``````int digit_to_int(char d)
{
char str[2];

str[0] = d;
str[1] = '\0';
return (int) strtol(str, NULL, 10);
}
``````

You could also use the `atoi()` function to do the conversion, once you have a string, but `strtol()` is better and safer.

As commenters have pointed out though, it is extreme overkill to call a function to do this conversion; your initial approach to subtract '0' is the proper way of doing this. I just wanted to show how the recommended standard approach of converting a number as a string to a "true" number would be used, here.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download