从字节数组中读取字节 [英] read bytes from byte array
问题描述
我有一个678560大小的字节数组。
i想要读取第0个索引到10478的数据。
无论如何,
是从指定位置读取数据到数据长度。
i为此编写代码,但我在谷歌尝试但没有得到完美答案。
i have a byte array of 678560 size.
i want to read data from 0th index to 10478.
is anyway to read data from specified position to length of data.
i wrote code for that but i tried in Google but didn't get perfect answer.
using (StreamReader r = new StreamReader(path))
{
string Readalltextofdata = r.ReadToEnd();
byte[] readalltextofdataintobytes = StringToByteArray(Readalltextofdata);
}
public static byte[] StringToByteArray(String hex)
{
int NumberChars = hex.Length;
byte[] bytes = new byte[NumberChars / 2];
for (int j = 0; j < NumberChars; j += 2)
bytes[j / 2] = Convert.ToByte(hex.Substring(j, 2), 16);
return bytes;
}
因此在readalltextofdataintobytes中创建并且大小为678560.现在从这个字节数组我想从第0位读到10478.
提前感谢。
so in readalltextofdataintobytes created and size is 678560. now from this byte array i want to read from 0th position to 10478.
thanks in advance.
推荐答案
使用 Linq
Use Linq
var someBytes = readalltextofdataintobytes.Take(10478).ToArray();
你也可以使用 Skip
跳过你不想要的字节阅读。
希望这会有所帮助,
Fredrik
You can also use Skip
to skip ahead past the bytes you don't want to read.
Hope this helps,
Fredrik
实际上是最有效的方法除了固定和不安全的代码之外,这是使用 Buffer.BlockCopy [ ^ ]方法。
在你的情况下,它将是:
Actually the most efficient way to do this, aside from pinning and unsafe code, is to use the Buffer.BlockCopy[^] method.
In your case, it would be:
byte[] source = //...
byte[] byteSection = new byte[10478];
Buffer.BlockCopy(source, 0, byteSection, 0, byteSection.Length);
复制更多/更少数据的方法只是改变byteSection数组的大小。
That way to copy more/less data just change the size of the byteSection array.
这篇关于从字节数组中读取字节的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!