【问题标题】:How do I convert from unicode to single byte in C#?如何在 C# 中从 unicode 转换为单字节?
【发布时间】:2010-04-12 20:17:17
【问题描述】:

如何在 C# 中将 unicode 转换为单字节?

这不起作用:

int level =1;
string argument;
// and then argument is assigned

if (argument[2] == Convert.ToChar(level))
{
    // does not work
}

还有这个:

char test1 = argument[2];
char test2 = Convert.ToChar(level);

产生时髦的结果。 test1 可以是:49 '1',而 test2 将是 1 ''

【问题讨论】:

标签: c# unicode char


【解决方案1】:

如何在 C# 中将 unicode 转换为单字节?

这个问题毫无意义,示例代码只会让事情变得更糟。

Unicode 是从字符到代码点的映射。代码点从 0x0 到 0x10FFFF 编号,远远超过单个字节所能存储的值。

示例代码有一个int、一个string和一个char。任何地方都没有bytes。

你真正想做什么?

【讨论】:

    【解决方案2】:

    使用UnicodeEncoding.GetBytes()

    UnicodeEncoding unicode = new UnicodeEncoding();
    Byte[] encodedBytes = unicode.GetBytes(unicodeString);
    

    【讨论】:

      【解决方案3】:

      charstring 在 .NET 中始终是 Unicode。你不能按照你尝试的方式去做。

      事实上,你想要完成什么?

      【讨论】:

        【解决方案4】:

        如果要测试 int level 是否匹配 char argument[2] 然后使用

          if (argument[2] == Convert.ToChar(level + (int)'0'))
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2010-10-08
          • 1970-01-01
          • 2013-08-21
          • 2015-07-20
          • 2018-08-28
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多