将List <boolean>转换为String

Max*_*imc 6 c# string boolean list

我得到了一个包含92个布尔值的布尔列表,我希望将列表转换为字符串,我想我将取8个布尔值(位)并将它们放入字节(8位)然后使用ASCII将其转换为字节将值添加到字符串然后将字符添加到字符串.然而,经过超过2个小时的googeling,没有运气atm.我尝试将列表转换为字节列表但它没有工作^^.

String strbyte = null;
for (int x = 0; x != tmpboolist.Count; x++) //tmpboolist is the 90+- boolean list
{
   //this loop checks for true then puts a 1 or a 0 in the string(strbyte)
   if (tmpboolist[x])
   {
      strbyte = strbyte + '1'; 
   }
   else
   {
      strbyte = strbyte + '0';
   }
}

//here I try to convert the string to a byte list but no success
//no success because the testbytearray has the SAME size as the 
//tmpboolist(but it should have less since 8 booleans should be 1 Byte)
//however all the 'Bytes' are 48 & 49 (which is 1 and 0 according to
//http://www.asciitable.com/)
Byte[] testbytearray = Encoding.Default.GetBytes(strbyte); 
Run Code Online (Sandbox Code Playgroud)

PS如果有人有更好的建议如何编码和解码布尔列表到字符串?(因为我希望人们用字符串分享他们的布尔列表,而不是90 1和0的列表.)

编辑:现在就开始了!所有的帮助

string text = new string(tmpboolist.Select(x => x ? '1' : '0').ToArray());
byte[] bytes = getBitwiseByteArray(text); //http://stackoverflow.com/a/6756231/1184013
String Arraycode = Convert.ToBase64String(bytes);
System.Windows.MessageBox.Show(Arraycode);
//first it makes a string out of the boolean list then it uses the converter to make it an Byte[](array), then we use the base64 encoding to make the byte[] a String.(that can be decoded later)
Run Code Online (Sandbox Code Playgroud)

我稍后会查看encoding32,再次获取所有帮助的信息:)

dtb*_*dtb 14

您应该将您的布尔值存储在BitArray中.

var values = new BitArray(92);
values[0] = false;
values[1] = true;
values[2] = true;
...
Run Code Online (Sandbox Code Playgroud)

然后,您可以将BitArray转换为字节数组

var bytes = new byte[(values.Length + 7) / 8];
values.CopyTo(bytes);
Run Code Online (Sandbox Code Playgroud)

和字节数组到Base64字符串

var result = Convert.ToBase64String(bytes);
Run Code Online (Sandbox Code Playgroud)

相反,您可以将Base64字符串转换为字节数组

var bytes2 = Convert.FromBase64String(result);
Run Code Online (Sandbox Code Playgroud)

和字节数组到BitArray

var values2 = new BitArray(bytes2);
Run Code Online (Sandbox Code Playgroud)

Base64字符串如下所示:"Liwd7bRv6TMY2cNE".这对于人们之间的分享来说可能有点不方便; 看看面向人类的base-32编码:

预期使用这些[base-32字符串]包括剪切和粘贴,文本编辑(例如在HTML文件中),通过键盘手动转录,通过纸笔手动转录,通过电话或收音机进行声音转录等.

这种编码的需求是:

  • 最小化转录错误 - 例如将'0'与'O'混淆的众所周知的问题
  • 嵌入到其他结构中 - 例如搜索引擎,结构化或标记文本,文件系统,命令shell
  • 简洁 - 较短的[字符串]比较长的字符串更好.
  • 人体工程学 - 人类用户(尤其是非技术用户)应尽可能轻松愉快地找到[字符串].[琴弦]看起来越丑,越糟糕.