如何在Windows Forms C#中将扩展ASCII转换为十进制?

我正在写一个Windows应用程序。 在将扩展ASCII [128-256]转换为十进制等效时遇到问题。

当我从jar文件中收到扩展的ASCII例如“Œ”时,它会进入C#应用程序,如下所示: 。

我可以知道如何将其转换为十进制等效值[ie] 140。

string textToConvert = "Œ"; Encoding iso8859 = Encoding.GetEncoding("iso-8859-1"); Encoding unicode = Encoding.Unicode; byte[] srcTextBytes = iso8859.GetBytes(textToConvert); byte[] destTextBytes = Encoding.Convert(iso8859,unicode, srcTextBytes); char[] destChars = new char[unicode.GetCharCount(destTextBytes, 0, destTextBytes.Length)]; unicode.GetChars(destTextBytes, 0, destTextBytes.Length, destChars, 0); System.String szchar = new System.String(destChars); MessageBox.Show(szchar); 

请帮我。 我该怎么办?

您的编码错误。 如Hans所指出的,iso-8859-1编码没有字符128-159。 根据这个问题 ,有3种编码包含您正在寻找的角色。 有iso-8859-15,Windows-1252,另一个用于mac。 由于这来自jar文件,因此,应该是os独立的,我会说正确的编码是iso-8859-15。

使用正确的编码,您对GetBytes的调用应返回包含小数值的数组。

首先,ISO-8859-1中的140是U + 008C – ISO-8859-1在数字和代码点之间有一对一的直接映射 – 而U + 008C是一个控制字符。 它着名的没有Œ (因为有争议的法国人不得不使用结扎,如果在通常情况下使用它,而Æ被包括在内,因为在某些语言中它意味着支持它是一个单独的字母“灰”而不是根据法语使用的结扎。脾气boost了)。

 string textToConvert = "Œ"; 

‘“Œ”’是一个字符串。 它与“扩展的ascii”无关。 它是由UTF-16在幕后实现的,但您甚至不应该将其视为这样,而是作为一个与数字,字节或编码无关的字符串,直到您开始阅读和写入为止流(如文件)。

  Encoding iso8859 = Encoding.GetEncoding("iso-8859-1"); 

如上所述,你当然不希望这样。 你可能想要GetEncoding("Windows-1252")因为这是一个匹配8859-1的Windows编码,除了它取出了一些控件并添加了一些更多的字母,包括位置140 Œ 。 我们假设你改变它……

 byte[] srcTextBytes = iso8859.GetBytes(textToConvert); 

好的,此时 – 如果您更改为使用CP-1252-您有一个单字节的字节数组,值140(0x8C)。

 byte[] destTextBytes = Encoding.Convert(iso8859,unicode, srcTextBytes); char[] destChars = new char[unicode.GetCharCount(destTextBytes, 0, destTextBytes.Length)]; unicode.GetChars(destTextBytes, 0, destTextBytes.Length, destChars, 0); System.String szchar = new System.String(destChars); MessageBox.Show(szchar); 

我不知道你在这里想做什么。 你从一个字符串开始,你以一个字符串结束,发生了什么?

让我们放弃这一点,从头开始。

如果你有一个字符串,并且你想在CP-1252中代表它的字节,那么:

 byte[] result = Encoding.GetEncoding("Windows-1252").GetBytes(inputString); 

如果你在CP-1252中有一些字节,并且你想要它们代表的字符串:

 string result = System.Text.Encoding.GetEncoding("Windows-1252").GetString(inputBytes); 

如果要在Windows-1252中读取或写入流(文件,网络流等),请使用使用该编码创建的StreamReader或StreamWriter:

 using(TextReader reader = new StreamReader(source, Encoding.GetEncoding("Windows-1252")); using(TextWriter writer = new StreamWriter(sink, Encoding.GetEncoding("Windows-1252")); 

我想你正在寻找这样的东西

  String str="œ"; var bytes = Encoding.GetEncoding("Windows-1252").GetBytes(s); string binStr = string.Join("", bytes.Select(b => Convert.ToString(b, 2))); int decimalEquivalent=Convert.ToInt32(binStr,2); Console.WriteLine(decimalEquivalent); 

这适用于ASCII [128-255]