Home >Backend Development >C++ >How Are Characters Represented Numerically in C?
Understanding the Numerical Representation of Characters in C
In C programming, characters are represented internally as numerical values. The American Standard Code for Information Interchange (ASCII) table assigns each character a specific numerical code. '0' corresponds to the ASCII value 48, while '1' has the value 49, and so on.
The ASCII Table and Character Codes
The ASCII table organizes these character codes in a tabular format, with numerical values ranging from 0 to 127 representing various characters, symbols, and control codes.
ASCII Value | Character | |
---|---|---|
48 | '0' | |
49 | '1' | |
57 | '9' |
Converting Character Codes to Numbers
The code snippet provided illustrates how subtracting '0' from the ASCII code of a character yields the numerical value it represents:
char c = '9'; int x = (int)(c - '0');
In this case, '9' has an ASCII code of 57. Subtracting '0', which has a code of 48, results in 9:
('9' - '0') = (57 - 48) = 9
Explanation
This works because ASCII codes for numerical characters ('0' through '9') are consecutive, with '0' having the lowest code. Subtracting '0' therefore effectively extracts the numerical value from the ASCII code.
For instance, if 'c' were '4', the ASCII equivalent of 52, the subtraction would yield:
('4' - '0') = (52 - 48) = 4
The above is the detailed content of How Are Characters Represented Numerically in C?. For more information, please follow other related articles on the PHP Chinese website!