foreach循环后的新行



此代码可以正常工作

foreach (char c in partToDecode)
{
var sum = c - 48;
if (sum > 40)
{
sum = sum - 8;
}
string suma = Convert.ToString(sum, 2).PadLeft(6, '0');
File.AppendAllText(@"C:UsersjakubPulpitbinary.txt", suma);
}

我们在for i循环内部是不可见的(我的意思是foreach和这条换行符在名为i的for循环内部(,所以我需要在foreach循环之后的for循环中有一条换行符。这段代码没有按我的意愿工作,我在开头有一行新行,第二行是纯文本,希望在每次完成foreach循环后都有一行换行

string sumaaa = Convert.ToString(sum, 2).PadLeft(6, '0');
File.AppendAllText(@"C:UsersjakubPulpitbinary.txt", sumaaa);
}
FileStream stream = new FileStream(@"C:UsersjakubPulpitbinary.txt", FileMode.Open);
StreamWriter sw = new StreamWriter(stream);
sw.Write("n");
sw.Close();
}

这有点小,之后我有一个代码,用于分割比特,将其小块转换为十进制。它早些时候起作用了,但我把它插入了一条评论中,现在它什么也没写。这个循环毕竟是独立的,在点击ok后运行,然后我有一个始终显示的form2,没有错误。

for (var k = 0; k < binlines.Count(); k++)
{       
var binline = binlines[k];
if (binline != null) //in case it was an empty line error (it's not)
{ 
string partmessage = binline.Substring(0, 6);
string partdecoded = Convert.ToInt32(partmessage, 2).ToString();
string partmessage2 = binline.Substring(6, 2);
string partdecoded2 = Convert.ToInt32(partmessage2, 2).ToString();
string partmessage3 = binline.Substring(8, 30);
string partdecoded3 = Convert.ToInt32(partmessage3, 2).ToString();
string so on to 15
File.AppendAllText(@"C:UsersjakubPulpitdecimal.txt", partdecoded + "," + partdecoded2 + "," partdecoded3 + "," + partdecoded4...)
}
else
{
}

现在我得到了一个超出范围的异常";索引和长度必须引用字符串"中的位置;

我建议一开始不要使用csv格式,而是将本地二进制数据写入磁盘。在这种情况下,您可以只使用BinaryReader和BinaryWriter,使其变得微不足道。

此外,可能值得制作一些更有效的方法或类来处理二进制数据到int.的读取

给定

public struct BinReader
{
private readonly string _line;
private int _index;
public BinReader(string line)
{
_line = line;
_index = 0;
}
public int GetInt(int length)
{
var result = Convert.ToInt32(_line.Substring(_index, length), 2);
_index += length;
return result;
}
}

用法

// some test data
var binLines = new List<string>()
{
Convert.ToString(1, 2) + Convert.ToString(2, 2) + Convert.ToString(3, 2) + Convert.ToString(4, 2) + Convert.ToString(5, 2),
Convert.ToString(1, 2) + Convert.ToString(2, 2) + Convert.ToString(3, 2) + Convert.ToString(4, 2) + Convert.ToString(5, 2),
};

// write to file
using (var sw = new BinaryWriter(new FileStream("SomeFileName.dat", FileMode.Create, FileAccess.ReadWrite)))
{
foreach (var reader in binLines.Select(line => new BinReader(line)))
{
sw.Write(reader.GetInt(1));
sw.Write(reader.GetInt(2));
sw.Write(reader.GetInt(2));
sw.Write(reader.GetInt(3));
sw.Write(reader.GetInt(3));
}
}
// read from file
using (var br = new BinaryReader(new FileStream("SomeFileName.dat", FileMode.Open, FileAccess.ReadWrite)))
{
foreach (var reader in binLines.Select(line => new BinReader(line)))
{
Console.WriteLine(br.ReadInt32());
Console.WriteLine(br.ReadInt32());
Console.WriteLine(br.ReadInt32());
Console.WriteLine(br.ReadInt32());
Console.WriteLine(br.ReadInt32());
}
}

证明它有效

1
2
3
4
5
1
2
3
4
5

相关内容

  • 没有找到相关文章

最新更新