Convert char to int in C#

后端 未结 14 807
情深已故
情深已故 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:01

    I am agree with @Chad Grant

    Also right if you convert to string then you can use that value as numeric as said in the question

    int bar = Convert.ToInt32(new string(foo, 1)); // => gives bar=2
    

    I tried to create a more simple and understandable example

    char v = '1';
    int vv = (int)char.GetNumericValue(v); 
    

    char.GetNumericValue(v) returns as double and converts to (int)

    More Advenced usage as an array

    int[] values = "41234".ToArray().Select(c=> (int)char.GetNumericValue(c)).ToArray();
    
    0 讨论(0)
  • 2020-11-22 11:03

    Try This

    char x = '9'; // '9' = ASCII 57
    
    int b = x - '0'; //That is '9' - '0' = 57 - 48 = 9
    
    0 讨论(0)
  • 2020-11-22 11:04

    I've seen many answers but they seem confusing to me. Can't we just simply use Type Casting.

    For ex:-

    int s;
    char i= '2';
    s = (int) i;
    
    0 讨论(0)
  • 2020-11-22 11:07

    By default you use UNICODE so I suggest using faulty's method

    int bar = int.Parse(foo.ToString());

    Even though the numeric values under are the same for digits and basic Latin chars.

    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2020-11-22 11:08

    This converts to an integer and handles unicode

    CharUnicodeInfo.GetDecimalDigitValue('2')

    You can read more here.

    0 讨论(0)
提交回复
热议问题