Birdman
Birdman

Reputation: 1524

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.

Upvotes: 2

Views: 2333

Answers (2)

Eser
Eser

Reputation: 12546

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.

Upvotes: 6

Aousaf Rashid
Aousaf Rashid

Reputation: 5738

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

If so, try this :

 string s = Encoding.ASCII.GetString(new byte[]{ i1 }); /// here i am keeping the end result a string 

Upvotes: 0

Related Questions