0

I have float data coming in as 33m/s. I stored them on Memory Stream so that I could calculate the average of stored data. However, I managed to stack float data to the memory stream by using this.

    byte[] FloatToByte = System.BitConverter.GetBytes(SomeData);
    memoryStream.Write(FloatToByte, 0, FloatToByte.Length);

Now my problem is that I want to get the float data that are stacked for 1second which would give me 33 float data stacked in the memory stream. I want to caculate the average of 33 float data. So how could I get the 33 float data from the memory stream? Can anyone help? Thank you

UPDATE I managed to solve the problem. Thank you for the answer that has been just wrote. I handled the problem by using queue. I wondered why I was trying to use memory stream. the first one who answered caught me on the mind thank you. For those who might be struggling like me, I am posting some code below.

     QueueForMicLeft.Enqueue(MicLeft_data);
            if(QueueForMicLeft.Count> 30)
            {
                AverageOfMicLeftData(QueueForMicLeft);
                Console.WriteLine("Average_data = " + AverageOfMicLeftData(QueueForMicLeft));
                QueueForMicLeft.Dequeue();
            }

    public static float AverageOfMicLeftData(IEnumerable<float> Collection)
    {
        float sum = 0;
        foreach (float obj in Collection)
            sum += obj;

        return (sum /30);
    }
  • 1
    Why are you writing it to a `MemoryStream` at all if that doesn't help you do what you want? Why not just use a `float[]`? You *can* convert a `MemoryStream` to a byte array just by calling `ToArray` but it's not clear that that's a good idea here... – Jon Skeet May 02 '17 at 11:37
  • You would BinaryReader.ReadSingle() to get it back, but as commented why convert a fully supported type in to its binary representation and then back again? – Alex K. May 02 '17 at 11:41
  • [Why queue](http://stackoverflow.com/q/8761238/1997232) ? The most optimal is *circular buffer* (`float[30]` + `int head, tail`), but as a starter `new List(30)` with size check will be good too. And as for an answer: you can answer own question. Please avoid to adding answer **into** the question (find a button "Post Your Answer" below). – Sinatr May 02 '17 at 12:29
  • Thanks for the comment next time I will do as what you said. I am new to stackoverflow. – K. Shinwook May 07 '17 at 23:03

0 Answers0