如何将 ASCII 值转换为 .NET 中的字符
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1574605/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to convert an ASCII value into a character in .NET
提问by demoncodemonkey
There are a million posts on here on how to convert a character to its ASCII value.
Well I want the complete opposite.
I have an ASCII value stored as an int and I want to display its ASCII character representation in a string.
这里有一百万篇关于如何将字符转换为其 ASCII 值的帖子。
好吧,我想要完全相反的。
我有一个存储为 int 的 ASCII 值,我想在字符串中显示其 ASCII 字符表示。
i.e. please display the code to convert the int 65to A.
即请显示将 int 转换65为A.
What I have currently is String::Format("You typed '{0}'", (char)65)
我目前拥有的是 String::Format("You typed '{0}'", (char)65)
but this results in "You typed '65'"whereas I want it to be "You typed 'A'"
但这导致"You typed '65'"而我希望它是"You typed 'A'"
I am using C++/CLI but I guess any .NET language would do...
我正在使用 C++/CLI,但我想任何 .NET 语言都可以...
(edited post-humously to improve the question for future googlers)
(死后编辑以改善未来谷歌员工的问题)
采纳答案by Austin Salonen
In C++:
在 C++ 中:
int main(array<System::String ^> ^args)
{
Console::WriteLine(String::Format("You typed '{0}'", Convert::ToChar(65)));
return 0;
}
回答by Guffa
There are several ways, here are some:
有几种方法,这里有一些:
char c = (char)65;
char c = Convert.ToChar(65);
string s = new string(65, 1);
string s = Encoding.ASCII.GetString(new byte[]{65});
回答by Marc Gravell
For ASCII values, you should just be able to cast to char? (C#:)
对于 ASCII 值,您应该能够转换为字符?(C#:)
char a = (char)65;
or as a string:
或作为字符串:
string a = ((char)65).ToString();
回答by BABA
Dim str as string
str = Convert.ToChar(65).ToString()
msgbox(str)
回答by yfeldblum
The complex version, of course, is:
当然,复杂的版本是:
public string DecodeAsciiByte(byte b) {
using(var w = new System.IO.StringWriter()) {
var bytebuffer = new byte[] { b };
var charbuffer = System.Text.ASCIIEncoding.ASCII.GetChars(bytebuffer);
w.Write(charbuffer);
return w.ToString();
}
}
Of course, that is before I read the answer using the Encoding.GetStringmethod. D'oh.
当然,那是在我使用该Encoding.GetString方法阅读答案之前。哦。
public string DecodeAsciiByte(byte b) {
return System.Text.Encoding.ASCII.GetString(new byte[] { b });
}
回答by mike01010
There are many ways to od this. If you wanted them to type consecutive digits w/op delimters and spaces, then you could use something like:
有很多方法可以解决这个问题。如果您希望他们输入带分隔符和空格的连续数字,那么您可以使用以下内容:
string userInput = "123456";
var digits = str.Select(c => Convert.ToInt32(c.ToString()));
回答by Michael Petrotta
Just cast it; couldn't be simpler.
就投吧;再简单不过了。
// C#
int i = 65;
Console.WriteLine((char)i);

