如何从 C # 中的 ASCII 字符代码中获取字符

我尝试用 C # 解析一个文件,该文件的字段(字符串)数组由 ASCII 字符代码0、1和2分隔(在 Visual Basic 6中,可以使用 Chr (0)或 Chr (1)等来生成这些字段(字符串)数组)

我知道对于 C # 中的字符代码0,您可以执行以下操作:

char separator = '\0';

但这对字符代码1和2不起作用吗?

327176 次浏览

Two options:

char c1 = '\u0001';
char c1 = (char) 1;

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];

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';