加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c# – 将List转换为String

发布时间:2020-12-15 18:32:04 所属栏目:百科 来源:网络整理
导读:我得到了一个包含92个布尔值的布尔列表,我希望将列表转换为字符串,我想我将取8个布尔值(位)并将它们放入字节(8位)然后使用ASCII将其转换为字节将值添加到字符串然后将字符添加到字符串.然而,经过超过2个小时的googeling,没有运气atm.我尝试将列表转换为字节
我得到了一个包含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);

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

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

string text = new string(tmpboolist.Select(x => x ? '1' : '0').ToArray());
byte[] bytes = getBitwiseByteArray(text); //https://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)

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

解决方法

您应该将布尔值存储在 BitArray中.
var values = new BitArray(92);
values[0] = false;
values[1] = true;
values[2] = true;
...

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

var bytes = new byte[(values.Length + 7) / 8];
values.CopyTo(bytes);

和字节数组到Base64字符串

var result = Convert.ToBase64String(bytes);

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

var bytes2 = Convert.FromBase64String(result);

和字节数组到BitArray

var values2 = new BitArray(bytes2);

Base64字符串如下所示:“Liwd7bRv6TMY2cNE”.这对于人们之间的分享来说可能有点不方便;看看human-oriented base-32 encoding:

Anticipated uses of these [base-32 strings] include cut-
and-paste,text editing (e.g. in HTML files),manual transcription via a
keyboard,manual transcription via pen-and-paper,vocal transcription over
phone or radio,etc.

The desiderata for such an encoding are:

  • minimizing transcription errors — e.g. the well-known problem of confusing
    ‘0’ with ‘O’
  • embedding into other structures — e.g. search engines,structured or
    marked-up text,file systems,command shells
  • brevity — Shorter [strings] are better than longer ones.
  • ergonomics — Human users (especially non-technical ones) should find the [strings] as easy and pleasant as possible. The uglier the [strings] looks,the worse.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读