【问题标题】:converting array of Unicode chars to an array of ASCII characters [closed]将Unicode字符数组转换为ASCII字符数组[关闭]
【发布时间】:2011-09-19 18:03:49
【问题描述】:

所以我对此的理解是 Unicode 字符有两个字节长,所以第一个字节应该是 ASCII 令牌,第二个字节应该是另一个 ASCII 令牌。我有一个 Unicode 字符数组,我想将其转换为一个 ASCII 字符数组,最终长度是原始字符的两倍。

【问题讨论】:

  • @Alan,这根本不是它的工作原理。请参阅this same question 以了解速成课程的问题形式。 :)
  • 您想将每个字符分成 2 个字节吗?还是要将字符串重新编码为 UTF-8?还是你想要别的?
  • (1) Unicode 字符最长可达 4 个字节(在 UTF-8 和 UTF-16 中)。
  • (2) ASCII 字符必须将高位设置为 0。Unicode 字符可以将每个字节的高位设置为 1。
  • @user319931:在 (2) 中,ASCII 字符 也是 Unicode 字符。反之亦然。在 (1) 中,我认为您对 Unicode 和 编码 感到非常困惑。 Unicode 代码点只是整数值,目前可以达到 0x10FFFF。

标签: c# arrays unicode ascii


【解决方案1】:

听起来您只想将 Unicode 字节拆分为两个 ASCII 字符。 字符串将不相关,字符根本不匹配。

Unicode 字符不是由两个 ASCII 标记组成。

Unicode 是一种不同于 ASCII 的编码。

但如果您只需要字节数据:Encoding.Unicode.GetBytes(data); 就是您所需要的。

【讨论】:

  • 赛德。谢谢您的答复。我正在阅读一个 ASCII 格式的文本文件,我正在使用 ReadBlock 方法,它给了我一个 char 数组。由于我的文件是 ASCII 格式的,我认为这样做是从文件中的前两个 ASCII 字符中获取字节数据,并将它们组合成一个 Unicode 字符,然后继续这样做。然后我的计划是获取每个元素并将其拆分为 ASCII 组件。这是错的吗?
  • @Alan 尝试使用带有 Encoding.ASCII 的 StreamReader 并用它读取文件。
【解决方案2】:

乔尔在这里说得最好:

http://www.joelonsoftware.com/articles/Unicode.html

我强烈建议阅读这篇文章。这是我见过的关于 Unicode 和字符集的最好的入门书。

【讨论】:

  • 天啊,我厌倦了这个!那篇文章是学习 Unicode 的一个很好的论据,但由于太不准确而不能成为一个好的 Unicode 介绍。
  • 当然,它有点老了。您能否提供任何资源来提供更好的 Unicode 入门或描述本文中的不准确之处?
【解决方案3】:

您可以使用Encoding.Convert 方法。使用它,您可以指定要转换字符串(或字符数组)的编码。

在他们的文档中可以看到这个例子:

使用系统; 使用 System.Text;

namespace ConvertExample
{
   class ConvertExampleClass
   {
      static void Main()
      {
         string unicodeString = "This string contains the unicode character Pi(\u03a0)";

         // Create two different encodings.
         Encoding ascii = Encoding.ASCII;
         Encoding unicode = Encoding.Unicode;

         // Convert the string into a byte[].
         byte[] unicodeBytes = unicode.GetBytes(unicodeString);

         // Perform the conversion from one encoding to the other.
         byte[] asciiBytes = Encoding.Convert(unicode, ascii, unicodeBytes);

         // Convert the new byte[] into a char[] and then into a string.
         // This is a slightly different approach to converting to illustrate
         // the use of GetCharCount/GetChars.
         char[] asciiChars = new char[ascii.GetCharCount(asciiBytes, 0, asciiBytes.Length)];
         ascii.GetChars(asciiBytes, 0, asciiBytes.Length, asciiChars, 0);
         string asciiString = new string(asciiChars);

         // Display the strings created before and after the conversion.
         Console.WriteLine("Original string: {0}", unicodeString);
         Console.WriteLine("Ascii converted string: {0}", asciiString);
      }
   }
}

【讨论】:

    猜你喜欢
    • 2015-03-29
    • 2022-01-09
    • 2022-01-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-11-19
    • 2018-11-18
    • 2021-05-24
    相关资源
    最近更新 更多