Conversion of characters to integers in C#
When dealing with characters in C#, you often need to convert characters into integers. However, using Convert.ToInt32
directly will return the decimal value of the character, not the numeric value.
Alternative conversion method:
While Convert.ToInt32
is typically used for string to integer conversion, it is not suitable for converting characters. Please consider the following alternatives:
Convert.ToInt32(new string(foo, 1))
: This method creates a new string from characters and then converts it to an integer using Convert.ToInt32
. int.Parse
: This method only works with strings, so you can convert the characters to a string first and then parse it into an integer. Native character to integer conversion:
C# also provides a native method to convert characters to integers:
<code class="language-csharp">char foo = '2'; int bar = foo - '0';</code>
Explanation:
This method relies on characters as the internal representation of numbers. The characters '0' to '9' occupy consecutive positions in the numeric sequence. By subtracting '0' from the character value you can get the actual numerical value.
In the above example, foo
represents the character '2', which has an internal value of 50. Subtract 48 (the ASCII value of '0') to get the integer 2.
This straightforward approach eliminates the need for intermediate string conversions, providing a direct and efficient way to convert C# characters to integers.
The above is the detailed content of How to Efficiently Convert a Character to its Integer Equivalent in C#?. For more information, please follow other related articles on the PHP Chinese website!