简体   繁体   English

MemoryStream并构造一个字节数组

[英]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: 我正在使用MemoryStream来构造我需要发送到服务器的字节数组。我有以下问题:

1) Is there a better way to construct an array of bytes than this ? 1)有没有比这更好的方法来构造一个字节数组?

2) Why this pice of code writes bogus in my memory stream ? 2)为什么这些代码会在我的内存流中写出伪造的?

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. 使用调试器,我看到在流中添加了值$ 6F32而不是$ 3E6C。

3) If i call 3)如果我打电话

MS.Position := 2;

and then i access PByte(MS.Memory)^ why do i get the first byte in the stream instead of the third? 然后我访问PByte(MS.Memory)^为什么我得到流中的第一个字节而不是第三个字节?

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. 我看到在流中添加了价值$ 6F32而不是$ 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. 按顺序添加到流中的4个字节是:$ 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. 因为Memory属性始终引用流的开头。 It does not take account of the stream's current position. 它没有考虑流的当前位置。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM