如何在C#中有效地获取字节数组的子集(前N个元素)? [英] How do I efficiently get a subset of a byte array (first N elements) in C#?

查看:29
本文介绍了如何在C#中有效地获取字节数组的子集(前N个元素)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个最大大小为1K的字节数组缓冲区.我想写出数组的一个子集(子集的开头始终是元素0,但我们感兴趣的长度是一个变量).

I have an byte array buffer of max size 1K. I want to write out a subset of the array (the start of the subset will always be element 0, but the length we're interested in is in a variable).

这里的应用程序是压缩.我将缓冲区传递给压缩函数.为简单起见,假设压缩将导致等于或小于1K字节的数据.

The application here is compression. I pass in a buffer to a compression function. For simplicity, assume the compression will lead to data that is equal, or less than 1K bytes.

byte[] buffer = new byte[1024];
while (true)
{
    uncompressedData = GetNextUncompressedBlock();
    int compressedLength = compress(buffer, uncompressedData);

    // Here, compressedBuffer[0..compressedLength - 1] is what we're interested in

    // There's a method now with signature Write(byte[] compressedData) that
    // I won't be able to change. Short of allocating a custom sized buffer,
    // and copying data into the custom sized buffer... is there any other
    // technique I could use to only expose the data I want?
}

我真的很想避免在这里复制-似乎完全没有必要,因为所有需要的数据已经在 buffer 中.

I'd really like to avoid a copy here -- it seems completely unnecessary as all of the data needed is in buffer already.

推荐答案

如果您无法更改方法签名,那么您将陷入困境.您不能在类型为byte [] 的字节数组上创建视图".理想的解决方案是对 ArraySegment< byte> byte [] 进行运算,然后加上一个偏移量和一个计数.如果您真的不能更改Write方法,那么很遗憾,您将不得不创建一个新数组并将数据复制到其中.

If you can't change the method signature, then you're stuck. You can't create a "view" over a byte array with type byte[]. The ideal solution for that would be for the operation to either take an ArraySegment<byte> or a byte[] followed by an offset and a count. If you really can't change the Write method, then unfortunately you're stuck with creating a new array and copying the data to it.

这篇关于如何在C#中有效地获取字节数组的子集(前N个元素)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆