C# Char 到 int 转换以获得 ASCII
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15283747/
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
Char to int conversion to get ASCII
提问by din
This may be an immature question, may be am missing something but my question is
这可能是一个不成熟的问题,可能我遗漏了一些东西,但我的问题是
Trying convert a char
to int
to get the ASCIIvalue of that char
, in most cases I get correct/expected ASCIIcode for particular char
, in some cases I don't. Can someone explain me why?
尝试将 a 转换char
为int
以获取ASCII值char
,在大多数情况下,我会得到特定的正确/预期的ASCII代码char
,在某些情况下我不会。有人可以解释我为什么吗?
Examples:
例子:
// Example 1:-
Console.WriteLine((int)'a');
// gives me 97 perfect!
// Example 2:-
Console.WriteLine((char)1); gives me ?
// now
Console.WriteLine((int )'?');
// this should give me 1, instead it gives me 9786 why?
this happens to ASCII > 127
or ASCII < 32
.
这发生在 ASCII >127
或 ASCII < 32
。
采纳答案by Alexei Levenkov
\01
is unprintable character, as result console is free to use any substitution to make it visible.
\01
是不可打印的字符,因此控制台可以自由使用任何替换来使其可见。
Also default Windows console is not very Unicode friendly, so strange things happen when you print characters outside of default printable ASCII range.
此外,默认的 Windows 控制台对 Unicode 不太友好,因此当您打印超出默认可打印 ASCII 范围的字符时,会发生奇怪的事情。
回答by Jon Skeet
Firstly, there's no such thing as "ASCII > 127" - ASCII only goes up to 127 (or 126; I can never remember whether delete is properly part of ASCII).
首先,没有“ASCII > 127”这样的东西——ASCII 只能达到 127(或 126;我永远记不起 delete 是否是 ASCII 的正确组成部分)。
Basically when you print out non-printable characters such as U+0001 ("Start of heading") it's up to the display device to determine what to do with that. Some consoles will print squares, some will print smileys, etc. You certainly shouldn't expect it to be reversible. You canexpect the conversion itself to be reversible in code though:
基本上,当您打印出诸如 U+0001(“标题开始”)之类的不可打印字符时,由显示设备决定如何处理。有些控制台会打印正方形,有些会打印笑脸等。您当然不应该期望它是可逆的。不过,您可以期望转换本身在代码中是可逆的:
char c = '\u0001';
int i = c; // i = 1
char d = (char) i;
Console.WriteLine(c == d); // True
回答by bobbymond
In answer to your question, why does Console.WriteLine((int )'?');
return 9786, it is because '?' in Unicode is represented by bytes 58 38, which as represented by an integer is 9786.
回答你的问题,为什么Console.WriteLine((int )'?');
返回9786,是因为'?' 在 Unicode 中用字节 58 38 表示,用整数表示为 9786。
Chars in c# are Unicode characters.
c# 中的字符是 Unicode 字符。