转换列表<布尔值>到字符串

发布于 2025-01-04 15:07:05 字数 1479 浏览 2 评论 0原文

我有一个包含 92 个布尔值的布尔列表,我希望将该列表转换为字符串,我想我将采用 8 个布尔值(位)并将它们放入一个字节(8 位)中,然后使用 ASCII 将其转换为字节value 为一个字符,然后将这些字符添加到一个字符串中。然而,在谷歌搜索了两个多小时后,没有运气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 如果有人对如何编码有更好的建议将布尔列表解码为字符串? (因为我希望人们用字符串分享他们的布尔列表,而不是 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)

我稍后会研究一下编码32,再次感谢所有帮助:)

I got a boolean list with 92 booleans, I want the list to be converted to a string, I thought I ll take 8 booleans(bits) and put them in a Byte(8 bits) and then use the ASCII to convert it the byte value to a char then add the chars to a string. However after googeling for more then 2 hours, no luck atm. I tried converting the List to a Byte list but it didn t work either ^^.

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 If anyone has a better suggestion on how to code & decode a Boolean list to a String?
(Because I want people to share their boolean list with a string rather then a list of 90 1 and 0s.)

EDIT: got it working now! ty all for helping

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)

I ll look into the encoding32 later, ty for all the help again :)

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

独闯女儿国 2025-01-11 15:07:05

您应该将布尔值存储在 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"。这对于人与人之间的共享来说可能有点不方便;看看面向人类的base-32编码

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

这种编码的需求是:

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

You should store your boolean values in a BitArray.

var values = new BitArray(92);
values[0] = false;
values[1] = true;
values[2] = true;
...

Then you can convert the BitArray to a byte array

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

and the byte array to a Base64 string

var result = Convert.ToBase64String(bytes);

Reversely, you can convert a Base64 string to a byte array

var bytes2 = Convert.FromBase64String(result);

and the byte array to a BitArray

var values2 = new BitArray(bytes2);

The Base64 string looks like this: "Liwd7bRv6TMY2cNE". This is probably a bit unhandy for sharing between people; have a look at 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.
梦中楼上月下 2025-01-11 15:07:05

首先,在这样的循环中连接字符串不是一个好主意 - 至少使用 StringBuilder,或者在 LINQ 中使用类似的东西

string text = new string(tmpboolist.Select(x => x ? '1' : '0').ToArray());

: 使用 LINQ 很容易,使用 string 实现 IEnumerable 的事实:

List<bool> values = text.Select(c => c == '1').ToList();

不清楚字节数组来自哪里......但是你不应该 尝试仅使用Encoding.GetString在字符串中表示任意二进制数据。那不是它的目的。

如果您不关心字符串使用什么格式,那么使用 Base64 会很好 - 但请注意,如果您将布尔值分组为字节,如果您需要区分“7 个值”,则需要额外的信息例如“8 个值,其中第一个为 False”。

To start with, it's a bad idea to concatenate strings in a loop like that - at least use StringBuilder, or use something like this with LINQ:

string text = new string(tmpboolist.Select(x => x ? '1' : '0').ToArray());

But converting your string to a List<bool> is easy with LINQ, using the fact that string implements IEnumerable<char>:

List<bool> values = text.Select(c => c == '1').ToList();

It's not clear where the byte array comes in... but you should not try to represent arbitrary binary data in a string just using Encoding.GetString. That's not what it's for.

If you don't care what format your string uses, then using Base64 will work well - but be aware that if you're grouping your Boolean values into bytes, you'll need extra information if you need to distinguish between "7 values" and "8 values, the first of which is False" for example.

胡大本事 2025-01-11 15:07:05

因为我从你的代码中推断你想要一个包含 n 位数字 1 或 0 的字符串,具体取决于内部列表 bool 值,那么怎么样...

public override string ToString()
{
    StringBuilder output = new StringBuilder(91);
    foreach(bool item in this.tempboolist)
    {
        output.Append(item ? "1" : "0");
    }
    return output.ToString();
}

警告这是即兴输入,我还没有使用编译器验证它!

Since I am infering from your code you want a string with n digits of either 1 or 0 depending onthe internal lists bool value then how about...

public override string ToString()
{
    StringBuilder output = new StringBuilder(91);
    foreach(bool item in this.tempboolist)
    {
        output.Append(item ? "1" : "0");
    }
    return output.ToString();
}

Warning this was off the cuff typing, I have not validated this with a compiler yet!

请叫√我孤独 2025-01-11 15:07:05

这个函数可以实现你想要的功能:

    public String convertBArrayToStr(bool[] input)
    {
        if (input == null)
            return "";
        int length = input.Count();
        int byteArrayCount = (input.Count() - 1) / 8 + 1;
        var bytes = new char[byteArrayCount];

        for (int i = 0; i < length; i++ )
        {
            var mappedIndex = (i - 1) / 8;
            bytes[mappedIndex] = (char)(2 * bytes[mappedIndex] +(input[i] == true ? 1 : 0));
        }
        return new string(bytes);
    }

This function does what you want:

    public String convertBArrayToStr(bool[] input)
    {
        if (input == null)
            return "";
        int length = input.Count();
        int byteArrayCount = (input.Count() - 1) / 8 + 1;
        var bytes = new char[byteArrayCount];

        for (int i = 0; i < length; i++ )
        {
            var mappedIndex = (i - 1) / 8;
            bytes[mappedIndex] = (char)(2 * bytes[mappedIndex] +(input[i] == true ? 1 : 0));
        }
        return new string(bytes);
    }
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文