开发者

Initialize byte array from a portion of existing byte array c#

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 开发者_JS百科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);


This is possible, but it requires unsafe code:

unsafe 
{
    byte[] b = new byte[buffersize];
    fixed(byte* bStart = b)
    {
       byte* header = bStart + 5;
       byte* data = bStart + 25;
    }
}

That being said, this is generally avoided unless absolutely necessary in C#. Using unsafe code is not the norm because it is, as suggested, not safe. This type of code can lead to many bugs, so it's best to rethink the design.


Sure there is.

int[] myArray = new[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
int[] subArray = myArray.Skip(5).ToArray();

The peformance characteristics are very different than your C example, however they are really not terrible. If you're looking for performance, than use unsafe as above, use the same array and simply begin iterating from the point in the list that you want, or use Array.Copy as shown elsewhere.


var arrOld = new byte[] { 0, 1, 2, 3, 5 };

int buffersize = 10;
var arrNew = new byte[buffersize];
Array.Copy(arrOld, arrNew, arrOld.Length);


You will need to use unsafe code in C#, which requires you to check the 'Allow unsafe code' option in the build settings.

unsafe
{
  byte[] b = new byte[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
  fixed (byte* pStart = b)
  {
    byte* pHeader = pStart + 2;
    byte* pData = pStart + 5;
  }
}


Be careful there: with your C code there was only ever one array. Your other array is really just a view into the original. If you really want two arrays, you can use Array.Copy(), like so:

char[] s = {'h', 'e', 'l', 'l', 'o', ' ', 'w', 'o', 'r', 'l', 'd'};
char[] b = new char[5];
Array.Copy(s, 6, b, 0, 5);

It's also worth mentioning that in c#, characters and bytes are very different things. Don't confuse them or you'll find yourself in trouble. Additionally, arrays are rarely the best option in C#. Use a class, a generic List, or even just an IEumerable instead.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜