0 0 Votes

Delphi/Lazarus: Load Byte Array from MemoryStream

Question by Guest | 09/01/2018 at 20:31

I have recently read the tutorial on byte arrays in Delphi and Lazarus. Very handy, but at the moment I'm desperate to load a TMemoryStream into such a byte array.

Given is a memory stream and I would like to copy the bytes from this stream into a byte array. Can somebody help me with it?

ReplyPositiveNegative

Delphian

Show Profile | Message
Avatar
1Best Answer
1 Vote

No problem, in the following example I will show you how to get the data from the memory stream into a byte array.

var
  MS: TStream;
  BA_IN, BA_OUT: array of Byte;
begin   
  
  // create some data
  SetLength(BA_IN, 2);
  BA_IN[0]:=$FF; 
  BA_IN[1]:=$FE;


  // create memory stream
  ms:=TMemoryStream.Create;

  try   
    // write data into the memory stream
    ms.WriteBuffer(BA_IN, 2);

    // read data from memory stream to byte array
    ms.Position := 0;
    SetLength(BA_OUT, ms.Size);
    ms.Read(BA_OUT[0], ms.Size);
  finally
    ms.Free;
  end; 

end;

To have something in our stream, we first write a few bytes into the stream (array BA_IN). Then we write the contents of the stream into the byte array BA_OUT.
09/01/2018 at 21:52

ReplyPositive Negative
Reply

Related Topics

Foreach Loop in Lazarus?
Question | 1 Answer

Important Note

Please note: The contributions published on askingbox.com are contributions of users and should not substitute professional advice. They are not verified by independents and do not necessarily reflect the opinion of askingbox.com. Learn more.

Participate

Ask your own question or write your own articles on askingbox.com. How to do.