Why is an extra 4 bytes added when using BlockCopy Method
After searching, I have failed to find out an easily understandable explaination as to why an extra 4 bytes added on when using BlockCopy method (as shown here, here, here, here)
The documentation says:
As its name suggests, the BlockCopy method copies a block of bytes as a whole, rather than copying one byte at a time. Therefore, if src and dst reference the same array, and the range from srcOffset + count -1 overlaps the range from dstOffset + count - 1, the values of the overlapping bytes are not overwritten before they are copied to the destination. In the following example, the values of bytes 0-16 in an array named arr are copied to bytes 12-28. Despite the overlapping range, the values of the source bytes are successfully copied.
However I don't really understand this clearly, and hoped someone would be kind enough to explain it differently (or post a link to a resource that explains this), and why the requirement exists to add these extra 4 bytes.
For clarity here is the code I am referring to:
As part of compress method:
byte[] gzBuffer = new byte[compressed.Length + 4];
System.Buffer.BlockCopy(compressed, 0, gzBuffer, 4, compressed.Length);
System.Buffer.BlockCopy(Bi开发者_开发问答tConverter.GetBytes(buffer.Length), 0, gzBuffer, 0, 4);
As part of decompress method:
ms.Write(gzBuffer, 4, gzBuffer.Length - 4);
It's not about BlockCopy
itself - it's about length-prefixing some data, that's all. You've found a bit of code that has been copied widely without being particularly well documented.
It's often useful when reading a "message" to know how long that message is before you start reading it - it means you don't need delimiters, or to hope that the end of the stream means the end of the data. This code just compresses the data, then writes the compressed length before the compressed data.
精彩评论