MemoryStream and building an array of bytes

I use a MemoryStream to build an array of bytes that I need to send to the server. I have some questions:

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

2) Why does this piece of code write fiction 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 the value $ 6F32 has been added to the stream instead of $ 3E6C.

3) If I call

 MS.Position := 2; 

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

+6
source share
1 answer

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

This is a very reasonable way to do this, in my opinion.


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

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


Why am I getting 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 into account the current position of the stream.

+9
source

Source: https://habr.com/ru/post/915281/


All Articles