从现有的字节数组C#中的部分初始化字节数组 [英] Initialize byte array from a portion of existing byte array c#

查看:353
本文介绍了从现有的字节数组C#中的部分初始化字节数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

时有一个简单的方法来从现有的字节数组的初始化部分字节数组。在C语言中,可以使用指针说喜欢

 字符S [10] =新的char [10];
字符* B = S + 5;
 

是否有可能做到这一点在C#中,如:

 字节[] B =新的字节[缓冲区大小]
BYTE *头= B + 5;
字节*数据= B + 25;
 

解决方案

ArraySegment&LT ; T> 结构提供了一个数组的视图,而无需创建一个副本。它不能在一个字节数组,预计地方使用,虽然。

  ArraySegment<字节> myArraySegment =新ArraySegment<字节>(myarray的,2,5);
 

如果你需要一个字节数组,你需要所需的值复制到一个新的数组实例,preferably使用的 Buffer.BlockCopy

 字节[] newArray =新的字节[5];
Buffer.BlockCopy(myArray的,2,newArray,0,5);
 

Is there are an easy way to initialize byte array from portion of existing byte array. In C language it is possible to use pointer to say like

char s[10] = new char[10];
char* b = s + 5;

Is it possible to do that in c#, like:

byte[] b = new byte[buffersize];
byte* header  = b + 5;
byte* data = b + 25;

解决方案

The ArraySegment<T> structure provides a view of an array without creating a copy. It cannot be used in places where a byte array is expected, though.

ArraySegment<byte> myArraySegment = new ArraySegment<byte>(myArray, 2, 5);

If you need a byte array, you need to copy the desired values to a new array instance, preferably using Buffer.BlockCopy:

byte[] newArray = new byte[5];
Buffer.BlockCopy(myArray, 2, newArray, 0, 5);

这篇关于从现有的字节数组C#中的部分初始化字节数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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