gpt4 book ai didi

c# - 将 List 转换为 String

转载 作者:太空狗 更新时间:2023-10-29 20:53:14 25 4
gpt4 key购买 nike

我得到一个包含 92 个 boolean 值的 boolean 列表,我想将该列表转换为字符串,我想我将取 8 个 boolean 值(位)并将它们放入一个字节(8 位)中,然后使用 ASCII 进行转换它的字节值到一个字符,然后将字符添加到一个字符串。然而,在谷歌搜索超过 2 小时后,没有运气 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 如果有人对如何将 boolean 列表编码和解码为字符串有更好的建议?(因为我希望人们使用字符串而不是 90 个 1 和 0 的列表来共享他们的 boolean 列表。)

编辑:现在开始工作了!请大家帮忙

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)

稍后我会研究 encoding32,再次寻求所有帮助:)

最佳答案

您应该将 boolean 值存储在 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.

关于c# - 将 List<boolean> 转换为 String,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9233132/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com