How to get a char from an ASCII Character Code in C#
309,409
Solution 1
Two options:
char c1 = '\u0001';
char c1 = (char) 1;
Solution 2
You can simply write:
char c = (char) 2;
or
char c = Convert.ToChar(2);
or more complex option for ASCII encoding only
char[] characters = System.Text.Encoding.ASCII.GetChars(new byte[]{2});
char c = characters[0];
Solution 3
It is important to notice that in C# the char type is stored as Unicode UTF-16.
From ASCII equivalent integer to char
char c = (char)88;
or
char c = Convert.ToChar(88)
From char to ASCII equivalent integer
int asciiCode = (int)'A';
The literal must be ASCII equivalent. For example:
string str = "Xสีน้ำเงิน";
Console.WriteLine((int)str[0]);
Console.WriteLine((int)str[1]);
will print
X
3626
Extended ASCII ranges from 0 to 255.
From default UTF-16 literal to char
Using the Symbol
char c = 'X';
Using the Unicode code
char c = '\u0058';
Using the Hexadecimal
char c = '\x0058';
Related videos on Youtube
Author by
Jimbo
Updated on July 08, 2022Comments
-
Jimbo almost 2 years
I'm trying to parse a file in C# that has field (string) arrays separated by ASCII character codes 0, 1 and 2 (in Visual Basic 6 you can generate these by using Chr(0) or Chr(1) etc.)
I know that for character code 0 in C# you can do the following:
char separator = '\0';
But this doesn't work for character codes 1 and 2?
-
ngoozeff over 13 yearsWhat about char sep = '\x32'; ?
-
Jon Skeet over 13 years@ngoozeff: I dislike
\x
for various reasons, and wouldn't suggest using it. -
Jon Skeet over 13 yearsGiven that we're talking about two specific values which are less than 128, the latter option seems unnecessarily long-winded. Unicode was designed to match ASCII.
-
Jimbo over 13 yearsLOL - It makes me depressed to give you even MORE points Jon, but thanks for the answer anyway :P
-
Danon about 9 yearsIt's good if you want to convert more than 1 byte or an array.
-
James S over 8 yearsProbably clear to everyone - but just to be explicit. In the first option in this answer the number is the character code in hexidecmal. in the 2nd option it is a decimal. Obviously 1(decimal) = 1(hex) but for higher codes it isn't! eg:
char c = '\u0021'
is equivalent tochar c = (char)33
is equivalent tochar c = '!'
-
Naveed Khan over 3 yearstry this System.Net.WebUtility.HtmlDecode(string c);
-
Jon Skeet over 3 years@NaveedKhan: No, that won't help. This isn't about HTML encoding or decoding.
-
Naveed Khan over 3 yearsyes you are right but this will going to convert every asci code within a string
-
Jon Skeet over 3 years@NaveedKhan: Not in the way that the question is about.