Err*_*eak 0 c# string unicode bits
我有一串比特,像这样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
Run Code Online (Sandbox Code Playgroud)
但输出文本只是完全混乱.怎么做对了?
您的代码存在一些问题.
首先BitArray将反转位顺序 - 它更容易使用
Convert.ToByte
您的输入字符串包含两个字节(每个字符一个),但您正在使用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);
Run Code Online (Sandbox Code Playgroud)