Cyr*_*yen 20 c# windows ascii function windows-forms-designer
我想创建一个用户输入数字的应用程序,程序将向用户返回一个字符.
编辑:如何反过来,将ascii字符更改为数字?
Far*_*yev 45
您可以使用以下方法之一将数字转换为ASCII/Unicode/UTF-16字符:
您可以使用这些方法将指定的32位有符号整数的值转换为其Unicode字符:
char c = (char)65;
char c = Convert.ToChar(65);
Run Code Online (Sandbox Code Playgroud)
此外,ASCII.GetString将字节数组中的字节范围解码为字符串:
string s = Encoding.ASCII.GetString(new byte[]{ 65 });
Run Code Online (Sandbox Code Playgroud)
请记住,ASCIIEncoding不提供错误检测.任何大于十六进制0x7F的字节都被解码为Unicode问号("?").
编辑:根据请求,我添加了一个检查,以确保输入的值在0到127的ASCII范围内.是否要限制这取决于您.在C#中(我相信.NET一般),chars使用UTF-16表示,因此任何有效的UTF-16字符值都可以转换为它.但是,系统可能不知道每个Unicode字符应该是什么样子,因此它可能显示不正确.
// Read a line of input
string input = Console.ReadLine();
int value;
// Try to parse the input into an Int32
if (Int32.TryParse(input, out value)) {
// Parse was successful
if (value >= 0 and value < 128) {
//value entered was within the valid ASCII range
//cast value to a char and print it
char c = (char)value;
Console.WriteLine(c);
}
}
Run Code Online (Sandbox Code Playgroud)
要将 ascii 转换为数字,您只需将 char 值转换为整数即可。
char ascii = 'a'
int value = (int)ascii
Run Code Online (Sandbox Code Playgroud)
变量值现在将有 97 对应于该 ascii 字符的值
(使用此链接作为参考) http://www.asciitable.com/index/asciifull.gif