Home >Backend Development >C++ >How Do I Efficiently Convert a Character to an Integer in C#?
In C#, Char is a unicode character that indicates a single letter, number or other symbols. Converting Char to an integer seems simple, but some subtle places may complicate the process.
As the questioner discovered, Convert.Toint32 () explained Char as its decimal value, and the returned results did not match the expected number. Int.parse () only accepts string, which further increases the complexity of the problem.
Native conversion method
Surprisingly, there is a simple native method in C# that can convert Char to int, and there is no need to perform string operations. This method includes subtracting '0' from Char: 0 ':
This method is effective because each character is represented by a number inside. The character's '0' to '9' is given continuous numbers, so the difference between '0' and '2' is 2, so as to get the required integer.
<code class="language-csharp">char foo = '2'; int bar = foo - '0';</code>This method is efficient and C# native method, making it a simple and direct method to convert Char into int.
The above is the detailed content of How Do I Efficiently Convert a Character to an Integer in C#?. For more information, please follow other related articles on the PHP Chinese website!