Convert char to int in C#

后端 未结 14 815
情深已故
情深已故 2020-11-22 10:44

I have a char in c#:

char foo = \'2\';

Now I want to get the 2 into an int. I find that Convert.ToInt32 returns the actual decimal value o

14条回答
  •  渐次进展
    2020-11-22 11:08

    This will convert it to an int:

    char foo = '2';
    int bar = foo - '0';
    

    This works because each character is internally represented by a number. The characters '0' to '9' are represented by consecutive numbers, so finding the difference between the characters '0' and '2' results in the number 2.

提交回复
热议问题