【问题标题】:reading a text file c# and delimited by size读取文本文件 c# 并按大小分隔
【发布时间】:2018-06-08 05:14:04
【问题描述】:

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

00001000100100000011000111

我知道我的消息的前两个数字是我的字符串 init = "00"

在我有 4 个数字之后,这意味着我的“消息数量”,例如我将发送“两个”消息 -> 0010 二进制数。

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

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

最后,我的字符串 end ="11"

消息需要像这样分开: 00 0010 0010 0100 00 0011 0001 11

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

有人可以帮助我吗?记住,对于这个例子,我只有“两个”消息,但我可以有“一个”或“三个”或.....

规则:如果我有多个“一个”消息,我需要使用“00”分隔

【问题讨论】:

标签: c# file text size csv


【解决方案1】:

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

【讨论】:

    【解决方案2】:

    试试这段代码(我尽可能地简化了代码,所以我认为它本身就足够干净了):

    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;
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-06-03
      • 2016-02-06
      • 2015-07-07
      • 2021-03-27
      • 1970-01-01
      • 1970-01-01
      • 2020-08-14
      • 1970-01-01
      相关资源
      最近更新 更多