Home >Backend Development >C++ >How Can I Efficiently Convert a Character Digit to an Integer?
Converting a Character to an Integer
Question:
How can I efficiently convert a single character into an integer value? Specifically, given a string of digits, I need to extract each one for use in calculations. Is there a better approach than using atoi()?
Answer:
Rather than converting the character to a string before calling atoi(), you can leverage the numerical representation of digits in character encoding. In most encodings, including ASCII, UTF-x, and others, the character encodings for digits are in sequential order, with '0' mapped to 48 and '9' mapped to 57.
This knowledge allows you to convert a digit character to an integer by simply subtracting its ASCII value from '0' (or 48). For example:
char c = '1'; int i = c - '0'; // i is now equal to 1, not '1'
This is equivalent to:
char c = '1'; int i = c - 48; // i is now equal to 1, not '1'
While both methods achieve the same result, the former (c - '0') is generally considered more readable due to its simplicity.
The above is the detailed content of How Can I Efficiently Convert a Character Digit to an Integer?. For more information, please follow other related articles on the PHP Chinese website!