How to convert an ascii character into an int in C

2019-02-11 22:24发布

问题:

How can I convert an ascii character into an int in C?

回答1:

What about:

int a_as_int = (int)'a';


回答2:

Are you searching for this:

int c = some_ascii_character;

Or just converting without assignment:

(int)some_aschii_character;


回答3:

I agree to Ashot and Cwan, but maybe you like to convert an ascii-cipher like '7' into an int like 7?

Then I recoomend:

char seven = '7';
int i = seven - '0'; 

or, maybe you get a warning,

int i = (int) (seven - '0'); 

corrected after comments, thanks.



回答4:

Use the ASCII to integer atoi() function:

#include <stdlib.h>

int num = atoi("23");


回答5:

A char value in C is implicitly convertible to an int. e.g, char c; ... printf("%d", c) prints the decimal ASCII value of c, and int i = c; puts the ASCII integer value of c in i. You can also explicitly convert it with (int)c. If you mean something else, such as how to convert an ASCII digit to an int, that would be c - '0', which implicitly converts c to an int and then subtracts the ASCII value of '0', namely 48 (in C, character constants such as '0' are of type int, not char, for historical reasons).



回答6:

You mean the ASCII ordinal value? Try type casting like this one:

int x = 'a';


回答7:

As everyone else told you, you can convert it directly... UNLESS you meant something like "how can I convert an ASCII Extended character to its UTF-16 or UTF-32 value". This is a TOTALLY different question (one at least as good). And one quite difficult, if I remember correctly, if you are using only "pure" C. Then you could start here: https://stackoverflow.com/questions/114611/what-is-the-best-unicode-library-for-c/114643#114643

(for ASCII Extended I mean one of the many "extensions" to the ASCII set. The 0-127 characters of the base ASCII set are directly convertible to Unicode, while the 128-255 are not.). For example ISO_8859-1 http://en.wikipedia.org/wiki/ISO_8859-1 is an 8 bit extensions to the 7 bit ASCII set, or the (quite famous) codepages 437 and 850.



回答8:

It is not possible with the C99 standard library, unless you manually write a map from character constants to the corresponding ASCII int value.

Character constants in C like 'a' are not guaranteed to be ASCII.

C99 only makes some guarantees about those constants, e.g. that digits be contiguous.

The word ASCII only appears on the C99 N1256 standard draft in footer notes, and footer note 173) says:

In an implementation that uses the seven-bit US ASCII character set, the printing characters are those whose values lie from 0x20 (space) through 0x7E (tilde); the control characters are those whose values lie from 0 (NUL) through 0x1F (US), and the character 0x7F (DEL).

implying that ASCII is not the only possibility