Home > Mobile >  TMemoryStream to array of bytes
TMemoryStream to array of bytes

Time:11-13

I'm attempting to get an array of bytes from a TMemoryStream. I'm struggling to understand how a memory stream works. To my understand I should just be able to loop through the MemoryStream using the Position and Size properties.

My expected result is to populate an array of bytes looping through the memory stream however when adjusting the Position property of the Memory stream it jumps from example 0 to 2 and then from 2 to 6.

Data.Position := 0;
repeat
   SetLength(arrBytes, Length(arrBytes)   1);

   Data.Read(arrBytes[High(arrBytes)], Data.Size);

   Data.Position := Data.Position   1;
until (Data.Position >= Data.Size -1);

The above code results in partial or in some cases just no data at all. How can I correctly convert the data from a memory stream to an Array of Byte

CodePudding user response:

When reading data from TMemoryStream or any other stream for that matter the position is automatically advanced by the number of bytes read.

From TMemoryStream.Read documentation

Reads up to Count bytes from the memory stream into Buffer and advances the current position of the stream by the number of bytes read.

So if you are reading data from TMemoryStream sequentially you don't have to change the memory position yourself as it is done automatically.

CodePudding user response:

@SilverWarior has provided more information on this topic and has made me able to figure out whats going.

I attempted to use 2 array types: array of Byte and TArray<Byte>. When I used those types the auto increment didn't work hence is why I manually incremented it. However the part that says "advances the current position of the stream by the number of bytes read" made me think. It doesn't increment because there are no bytes to read.

I eventually did following using the TBytes type and it has solved my problem.

var
  arrBytes: TBytes;

  SetLength(arrBytes, Data.Size);
  Data.Read(arrBytes, Data.Size);
  • Related