读取文本文件 c# 并按大小分隔

reading a text file c# and delimited by size

下面是我的文本文件的数据示例

00001000100100000011000111

我知道我消息的前两个数字是我的字符串 init = "00" <- 总是这些数字。

在我有 4 个数字后,这意味着我的 "message quantity" 如果我将发送 "two" 消息 -> 0010 二进制数。

收到第一条消息“24”后,代码为“0010 0100”二进制数。

比起我的第二条消息“31”,代码是“0011 0001”但在输入这些数字之前我必须使用“00”分隔。

最后,我的字符串结束 ="11" <- 总是这些数字

邮件需要像这样分开: 00 0010 0010 0100 00 0011 0001 11

我必须阅读此文件并显示消息内容。 “24”和“31”。

有人可以帮助我吗?记住,对于这个例子,我只有 "two" 消息,但我可能有 "one" 或 "three" 或 .....

规则:如果我有超过"one"条消息,我需要用“00”分隔

将它们作为字符串加载进来,使用子字符串字符串方法,并按大小抓取子字符串。但是,您的实际消息必须具有相同的长度,或者您还需要一个长度指示符来指定消息何时结束。因为 00,可能是实际消息的一部分。

试试这个代码(我尽量保持代码最简单,所以我认为它本身就足够干净了):

static void Main(string[] args)
{
    List<int> messages = new List<int>();

    int blockSize = 4;

    string binary = "00001000100100000011000111";

    int howManyMessages = BinToInt(binary.Substring(2, blockSize));
    // if there is no messages, return
    if (howManyMessages == 0) return;
    // read first message
    int firstMessage = BinToInt(binary.Substring(2 + blockSize, 2 * blockSize));
    messages.Add(firstMessage);
    // if there is just one message, we just read it, so end
    if (howManyMessages == 1) return;
    // read the rest of messages
    for (int i = 2; i <= howManyMessages; i++)
        messages.Add(BinToInt(binary.Substring(2 + blockSize + 2 * (1 + blockSize), 2 * blockSize)));

    Console.ReadKey();
}
// convert binary number in string to integer
private static int BinToInt(string bin)
{
    int result = 0;
    for (int i = 0; i < bin.Length; i++)
        result += int.Parse(bin[bin.Length - 1 - i].ToString()) * (int)Math.Pow(2, i);
    return result;
}