Conversion of characters to integers in C#
In C#, converting character variables to integers can be a bit tricky. Convert.ToInt32()
The function returns the decimal value of the character, not the actual number. To obtain the desired result, the characters must be converted to strings before using Convert.ToInt32()
.
However, a more efficient method is to use the following formula:
<code class="language-csharp">int bar = foo - '0';</code>
In this formula, the character variable foo
represents the character value, and '0'
represents the ASCII code of the character '0'
. By subtracting the ASCII code of '0'
from the ASCII code of the character, we get the numerical value of the character.
Example:
<code class="language-csharp">char foo = '2'; int bar = foo - '0';</code>
Here, the ASCII code of '2'
is 50 and the ASCII code of '0'
is 48. Subtract 48 from 50 to get 2, which is the desired value.
The above is the detailed content of How Can I Efficiently Convert a Char to an Int in C#?. For more information, please follow other related articles on the PHP Chinese website!