Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MemoryStream and constructing an array of bytes

I am using a MemoryStream to construct an array of bytes i need to send to a server.I have thre questions:

1) Is there a better way to construct an array of bytes than this ?

2) Why this pice of code writes bogus in my memory stream ?

var
  serial : word;
  MS : TMemoryStream;
const
  somebytes : array [0..1] of byte = ($72,$72);
...
begin
      MS := TMemoryStream.Create();
      try
      MS.Write(somebytes[0],2);
      serial := $3E6C;
      MS.Write(serial,2);
      finally
      MS.Free;
end;

Using the debugger i see that in the stream is added the value $6F32 instead of $3E6C.

3) If i call

MS.Position := 2;

and then i access PByte(MS.Memory)^ why do i get the first byte in the stream instead of the third?

like image 854
opc0de Avatar asked May 09 '12 11:05

opc0de


People also ask

Does MemoryStream copy byte array?

From expirience I can say, that it does not copy the array. Be aware though, that you are unable to resize the memory stream, when using an array in the constructor.

How do I get bytes from MemoryStream?

To get the entire buffer, use the GetBuffer method. This method returns a copy of the contents of the MemoryStream as a byte array. If the current instance was constructed on a provided byte array, a copy of the section of the array to which this instance has access is returned.

What is a MemoryStream?

MemoryStream encapsulates data stored as an unsigned byte array. The encapsulated data is directly accessible in memory. Memory streams can reduce the need for temporary buffers and files in an application. The current position of a stream is the position at which the next read or write operation takes place.

What is the difference between MemoryStream and FileStream?

As the name suggests, a FileStream reads and writes to a file whereas a MemoryStream reads and writes to the memory. So it relates to where the stream is stored.


1 Answers

Is there a better way to construct an array of bytes than this?

That's a perfectly reasonable way to do it, in my view.


I see that in the stream is added the value $6F32 instead of $3E6C.

Check again. The correct values are in fact added. But beware of the traps of little endian data types. The 4 bytes added to your stream, in order, are: $72, $72, $6C, $3E.


Why do I get the first byte in the stream instead of the third?

Because the Memory property always refers to the beginning of the stream. It does not take account of the stream's current position.

like image 66
David Heffernan Avatar answered Oct 13 '22 00:10

David Heffernan