【发布时间】:2012-03-03 05:43:01
【问题描述】:
我有一个包含 92 个布尔值的布尔列表,我希望将列表转换为字符串,我想我会取 8 个布尔值(位)并将它们放在一个字节(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 如果有人对如何将布尔列表编码和解码为字符串有更好的建议? (因为我希望人们用字符串而不是 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)
稍后我将研究 encoding32,再次寻求所有帮助 :)
【问题讨论】:
-
您需要更具体地说明您希望字符串的外观
-
不清楚你想得到什么。一个字符串,它是位的 ascii 编码,然后可以转回布尔值?
-
Encoding.Default.GetBytes不会像您认为的那样做。看到这个问题:stackoverflow.com/questions/2989695/… -
如果你想用字符串表示布尔列表,我建议使用十六进制字符 (0-9, af),它将 4 位打包到每个字符中,而不是将 8 位打包到一个字符中.如果将 8 位打包成一个 char,这将使用 8 位 ascii 的全部范围,其中包括一些不可打印的字符。例如。值 00000111 = 7 = 响铃字符。最好表示为 0000 0111 => "07"。
-
请注意,92 不能被 8 整除。您将需要处理 4 个孤立位。