Search code examples
c#unicodechartype-conversionint

C#: Convert int to char, but in literal not unicode representation


I am trying to convert intergers into characters. But the problem is from what I can tell whenever I convert it turns it into the unicode representation of the char. For example:

        int i1 = 3;

        char c1 = (char)i1;
        //also tried: char c1 = Convert.ToChar(i1)

        Console.WriteLine(c1);

This is what I'm seeing when I debug:

enter image description here

It shows 3, which is exactly what I want, I want int 3 to be converted into char '3', but instead it's the unicode representation, '\u0003'. So when I try to print this it results in garbage. I can't seem to find the solution anywhere.


Solution

  • If I get you correctly, this is what you want

    int i1 = 3;
    char c = (char)(i1 + '0');
    
    Console.WriteLine(c);
    

    '0' is 48 in ASCII. Adding 3 to 48 is 51 and converting 51 to char is 3.