How to cast int digit to char without loosing digit value in c#

前端 未结 3 1612
一整个雨季
一整个雨季 2020-12-11 12:12

Mabby it\'s a stupid question, but how can I cast digit of type int to digit of type char?

Standard conversion OPs doesn\'t do this:

int x = 5         


        
3条回答
  •  隐瞒了意图╮
    2020-12-11 13:04

    Add 48 to your int value before converting to char:

    char c = (char)(i + 48);
    

    Or for int[] -> char[] conversion:

    var source = new int[] { 1, 2, 3 };
    var results = source.Select(i => (char)(i + 48)).ToArray();
    

    It works, because '0' character in ASCII table has 48 value. But it will work only if your int values is between 0 and 9.

提交回复
热议问题