【问题标题】:Convert a Binary String longer than 8 into a single unicode character将长度超过 8 的二进制字符串转换为单个 unicode 字符
【发布时间】:2018-01-11 08:59:24
【问题描述】:

我需要将字符串转换为二进制并返回。 但是当输入是Unicode Character 时,生成的二进制字符串长度超过 8 个字符,使用Convert.ToByte 将其转换回来会导致Overflow Exception。 我使用Convert.ToString方法将String转换为Binary。

String input = "⌓" //Unicode Character
String binary = Convert.ToString(input, 2); //Convert to Binary 
                                           //->> Returns "10001100010011"
byte re = Convert.ToByte("10001100010011", 2); //This causes an Overflow Exception 
//What should I do here? Is there a better reverse of Convert.ToString than Convert.ToByte?

是否有替代方案或类似的东西?

【问题讨论】:

  • Convert.ToInt16?它有 2 个字节长。
  • Convert.ToString(Char.ConvertToUtf32(input, 0), 2); Char.ConvertFromUtf32(Convert.ToInt32(..., 2)),如果你想覆盖所有的 Unicode 并且不想特别对待代理。
  • 谢谢 Jeroen,效果很好

标签: c# .net encoding binary type-conversion


【解决方案1】:

我认为这里的问题是一个字节只有 8 位。您正在输入一个包含 14 位的字符串。尝试使用 Convert.ToUint16() 并将“re”声明为 Uint16,如下所示:

UInt16 re = Convert.ToUInt16("10001100010011", 2); 
// UInt16 is large enough to hold the data

Console.WriteLine(re); // prints 8979

//unicode decimal 8979: http://www.codetable.net/decimal/8979

【讨论】:

    猜你喜欢
    • 2016-07-21
    • 1970-01-01
    • 2014-12-15
    • 1970-01-01
    • 1970-01-01
    • 2014-08-02
    • 1970-01-01
    • 2021-02-24
    相关资源
    最近更新 更多