【问题标题】:String of bits to Unicode位字符串到 Unicode
【发布时间】:2015-02-27 10:45:58
【问题描述】:

我有一串位,像这样string str = "0111001101101000" 是字母“sh”。
我需要用它制作 Unicode 字母。我正在做以下事情:

BitArray bn = new BitArray(str.Length); //creating new bitarray
for (int kat = 0; kat < str.Length; kat++)
{
    if (str[kat].ToString() == "0")//adding boolean values into array
    {
        bn[kat] = false;
    }
    else
        bn[kat] = true;
}

byte[] bytes = new byte[bn.Length];//converting to bytes
bn.CopyTo(bytes, 0);
string output = Encoding.Unicode.GetString(bytes); //encoding                          

textBox2.Text = output; // result in textbox

但输出文本完全是一团糟。怎么做才对?

【问题讨论】:

  • 预期的结果是什么?
  • 正如我所说,“这是字母“sh”。”,所以,我期待字母“sh”。我得到了问号、象形文字等。
  • 您使用的是什么编码? “sh”的UTF8给我“1100111000010110”,代码在这里,ideone.com/UdvG6r
  • 您可以在下面的答案中看到我做错了什么。
  • 基本上你的字符串是 UTF8 的字节序错误。

标签: c# string unicode bits


【解决方案1】:

您的代码存在一些问题。

  1. 第一个 BitArray 将反转位顺序 - 它更易于使用 Convert.ToByte

  2. 您的输入字符串包含两个字节(一个 每个字符),但您使用 Encoding.Unicode 对其进行解码, 是UTF16编码(每个字符两个字节),需要使用Encoding.UTF8

工作代码

string str = "0111001101101000";

int numOfBytes = str.Length / 8;
byte[] bytes = new byte[numOfBytes];
for (int i = 0; i < numOfBytes; ++i)
{
    bytes[i] = Convert.ToByte(str.Substring(8 * i, 8), 2);
}

string output = Encoding.UTF8.GetString(bytes);     

【讨论】:

    【解决方案2】:

    A) 您的字符串是 ASCII,而不是 UNICODE:每个字符 8 位

    B) 每个字节的最高有效位在左侧,所以 bn[...] 中使用的奇怪数学运算

    C) 注释部分没有用,因为“false”是BitArray的默认状态

    D) 字节数组的长度错误。 8 位 == 1 个字节! :-)

    string str = "0111001101101000";
    
    BitArray bn = new BitArray(str.Length); //creating new bitarray
    
    for (int kat = 0; kat < str.Length; kat++) {
        if (str[kat] == '0')//adding boolean values into array
        {
            //bn[(kat / 8 * 8) + 7 - (kat % 8)] = false;
        } else {
            bn[(kat / 8 * 8) + 7 - (kat % 8)] = true;
        }
    }
    
    // 8 bits in a byte
    byte[] bytes = new byte[bn.Length / 8];//converting to bytes
    bn.CopyTo(bytes, 0);
    
    string output = Encoding.ASCII.GetString(bytes); //encoding    
    

    可能更好:

    string str = "0111001101101000";
    
    byte[] bytes = new byte[str.Length / 8];
    
    for (int ix = 0, weight = 128, ix2 = 0; ix < str.Length; ix++) {
        if (str[ix] == '1') {
            bytes[ix2] += (byte)weight;
        }
    
        weight /= 2;
    
        // Every 8 bits we "reset" the weight 
        // and increment the ix2
        if (weight == 0) {
            ix2++;
            weight = 128;
        }
    }
    
    string output = Encoding.ASCII.GetString(bytes); //encoding    
    

    【讨论】:

      猜你喜欢
      • 2017-11-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-03-15
      • 1970-01-01
      • 2023-03-30
      • 2012-07-26
      • 2019-05-12
      相关资源
      最近更新 更多