Converting a Char to an Int without String Intermediaries
Programmers often face the task of extracting numerical digits from a character string to utilize them in calculations. While accessing individual characters by index is straightforward, the question arises: how can these characters be converted into integers?
The traditional approach involves using the atoi() function, which takes a string as an argument. However, this necessitates converting each character to a string first. Is there a more efficient method?
Leveraging Character Encodings
The answer lies in exploiting the fact that the character encodings for digits are sequential, ranging from 48 (for '0') to 57 (for '9'). This consistency holds across various encodings, including ASCII, UTF-x, and most others.
Therefore, the integer equivalent of a digit character is simply the character minus '0', or 48.
Consider the following code snippet:
char c = '1'; int i = c - '0'; // i is now equal to 1, not '1'
This code assigns the integer value 1 to the variable i. Alternatively, the following code snippet achieves the same result:
char c = '1'; int i = c - 48; // i is now equal to 1, not '1'
While both methods produce the desired result, the subtraction from '0' is considered more readable and efficient.
The above is the detailed content of How Can I Efficiently Convert a Character Digit to an Integer without Using Strings?. For more information, please follow other related articles on the PHP Chinese website!