[英]C# - Are type conversions (numbers to char) made based on ASCII values?
I'm new to C#, and I'm trying to understand more about data types and conversion. 我是C#的新手,我想进一步了解数据类型和转换。 I have the following console program:
我有以下控制台程序:
using System;
namespace First_lesson
{
class Program
{
static void Main(string[] args)
{
char singleLetter = 'B';
short num = 291;
Console.WriteLine("{0} {1}", num, singleLetter);
singleLetter = Convert.ToChar(num);
Console.WriteLine(singleLetter);
Console.WriteLine("{0} {1}", sizeof(short), sizeof(char));
}
}
}
I don't understand why, when I convert num
to a char
, I get a lowercase g instead of the hashtag symbol # . 我不明白为什么,将
num
转换为char
,会得到小写的g而不是#号 。
Isn't the conversion made based on ASCII values? 转换不是基于ASCII值进行的吗?
Convert.ToChar
returns a char
(which is a UTF-16 code unit) that has the specified numeric value. Convert.ToChar
返回具有指定数值的char
(这是UTF-16代码单元)。
291
(decimal) is the same as 0x123
(hex), so Convert.ToChar(291)
returns a char
containing the character U+0123
, which is LATIN SMALL LETTER G WITH CEDILLA, ie, ģ
. 291
(十进制)与0x123
(十六进制)相同,因此Convert.ToChar(291)
返回一个包含字符U+0123
的char
,该字符是带有CEDILLA的拉丁文小写字母G,即ģ
。
When you print this to a non-Unicode console, the accent is stripped off and an ASCII g
is printed instead. 当您将其打印到非Unicode控制台时,会去除重音符号,而是打印ASCII
g
。
The char keyword is used to declare an instance of the System.Char structure that the .NET Framework uses to represent a Unicode character.
char关键字用于声明System.Char结构的实例,.NET Framework使用该实例表示Unicode字符。 The value of a Char object is a 16-bit numeric (ordinal) value.
Char对象的值是16位数字(常规)值。
Actually, one char represents a Unicode
character. 实际上,一个字符代表一个
Unicode
字符。 35 in decimal is the representation of #
sign 小数点后的35是
#
号的表示
public static void Main()
{
char singleLetter = 'B';
short num = 35;
Console.WriteLine("{0} {1}", num, singleLetter);
singleLetter = Convert.ToChar(num);
Console.WriteLine(singleLetter);
Console.WriteLine("{0} {1}", sizeof(short), sizeof(char));
Console.ReadLine();
}
Try this: 尝试这个:
short singleLetter = Convert.ToInt16('B');
Console.WriteLine(singleLetter);
B
is the 66
decimal value You can use this page as a reference for the Unicode
table B
是66
十进制值您可以使用此页面作为Unicode
表的参考
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.