Home >Backend Development >C++ >How Does Subtracting '0' Convert a Character Digit to its Numeric Value in C?
Number Conversion in C: Subtracting '0' to Extract Numeric Value
In C, every character, including digits, is represented by an integer known as an ASCII (American Standard Code for Information Interchange) value. The '0' character has an ASCII value of 48, which serves as the starting point for all numerical characters.
When you subtract '0' from the ASCII value of a character, the result is the numeric value that the character represents. This is because the ASCII codes for digits are structured in a sequential manner, with each subsequent digit having a value that is one greater than the previous one.
For instance:
char c = '9'; int x = (int)(c - '0');
Here, the ASCII value of '9' is 57. When we subtract '0' (48) from this value, we get 57 - 48 = 9. Therefore, the variable x will be assigned the numerical value 9.
The reason for this behavior is that the ASCII codes for digits are contiguous, meaning they follow a linear sequence. Subtracting the starting value ('0') effectively aligns the numeric value with its corresponding ASCII code.
The ASCII table, which maps characters to their corresponding integer values, illustrates this concept clearly:
'0' -> 48 '1' -> 49 '2' -> 50 ... '9' -> 57
By subtracting '0' from the ASCII value of any digit, you can obtain its numeric representation. This technique is frequently employed in C programming to extract numerical values from character data.
The above is the detailed content of How Does Subtracting '0' Convert a Character Digit to its Numeric Value in C?. For more information, please follow other related articles on the PHP Chinese website!