C# How to extract bytes from byte array? With know

2019-08-27 16:01发布

问题:

I need to get specific bytes from a byte array. I know the content of the first byte I want and I need x bytes after that.

For example, I have

byte [] readbuffer { 0, 1, 2, 0x55, 3, 4, 5, 6};
byte [] results = new byte[30];

and I need the 3 bytes that appear after "0x55"

byte results == {ox55aa, 3, 4, 5}

I'm using:

Array.copy(readbuffer, "need the index of 0x55" ,results, 0, 3);

I need to find the index of 0x55

PS: 0x55 is in an aleatory position in the array. PS2: I forgot to mention before that I'm working in .Net Micro Framework.

(I'm sorry for the non code description, I'm a very newbie to programming... and english)

thank you in advance

[edited]x2

回答1:

This can be achieved like this:

byte[] bytes = new byte[] { 1, 2, 3, 4, 0x55, 6, 7, 8 };
byte[] newBytes = new byte[4];
Buffer.BlockCopy(bytes,Array.IndexOf(bytes,(byte)0x55), newBytes,0,4);


回答2:

I guess you simply need to search the whole array for the specific value and remember the index where you find it...

int iIndex = 0;  
for (; iIndex < valuearray.Length; iIndex++);
  if (valuearray[iIndex] == searchedValue) break;

and from here on do what you want with the found index.

P.S. maybe there are slight syntax failures, as I usually use C++.net



回答3:

        byte[] results = new byte[16];
        int index = Array.IndexOf(readBuffer, (byte)0x55);
        Array.Copy(readBuffer, index, results, 0, 16);

Thank you all.

This is my code now. it's working as I expect :)