你怎么做呢?给定一个字节数组:
byte[] foo = new byte[4096];
Run Code Online (Sandbox Code Playgroud)
如何将数组的前x个字节作为单独的数组?(具体来说,我需要它作为一个IEnumerable<byte>)
这是为了与Sockets合作.我认为最简单的方法是数组切片,类似于Perls语法:
@bar = @foo[0..40];
Run Code Online (Sandbox Code Playgroud)
这会将前41个元素返回到@bar数组中.C#中有些东西我只是缺少,还是还有其他一些我应该做的事情?
LINQ对我来说是一个选项(.NET 3.5),如果这有帮助的话.
我在内存中有一个字节数组,从文件中读取.我想在某个点(索引)拆分字节数组,而不必只创建一个新的字节数组并一次复制每个字节,从而增加了操作的内存占用量.我想要的是这样的:
byte[] largeBytes = [1,2,3,4,5,6,7,8,9];
byte[] smallPortion;
smallPortion = split(largeBytes, 3);
Run Code Online (Sandbox Code Playgroud)
smallPortion将等于1,2,3,4
largeBytes将等于5,6,7,8,9
我有一个最大大小为1K的字节数组缓冲区.我想写出数组的一个子集(子集的开头总是元素0,但我们感兴趣的长度是变量).
这里的应用程序是压缩.我将缓冲区传递给压缩函数.为简单起见,假设压缩将导致数据相等或小于1K字节.
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?
}
Run Code Online (Sandbox Code Playgroud)
我真的很想在这里避免复制 - …
我已经从SO中读过几个不同的问题,但仍然无法使其发挥作用.我正在使用public static string[] files = Directory.GetFiles(CurrentDirectory, "*.wav", SearchOption.AllDirectories);一个文件路径数组,然后将其传递给文件流.只有一个线程处理所有文件,文件流所做的操作耗时太长.所以我决定拆分数组并将那些较小的数组传递给不同的线程.
我使用的代码来自另一个SO问题,并用它来传递split数组,但它只能在第一个数组中只使用一个文件,但我知道问题是什么:
var thing = from index in Enumerable.Range(0, files.Length)
group files[index] by index/600;
foreach(var set in thing)
string.Join(";", set.ToArray());
Run Code Online (Sandbox Code Playgroud)
(这不完全是我使用它的方式,我已经把它弄得太乱了,我记不住了.)这个问题是所有东西都被视为一个巨大的文件路径,我有一个foreach循环,每个来自较小数组的文件,但它将其中的每个文件视为一个文件,当搜索返回多个文件时抛出filepathtoolong异常.我的函数接受一个数组然后foreach (string file in smallerArray)用来写入每个数组.我需要做的是将文件数组分成4个较小的数组并启动新的线程,new Thread(() => { DoWork(newArray); }).Start();但我尝试过的任何工作都没有.