C# How to extract bytes from byte array? With known starting byte

别等时光非礼了梦想. 提交于 2019-12-11 17:38:58

问题


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 :)



来源:https://stackoverflow.com/questions/28499778/c-sharp-how-to-extract-bytes-from-byte-array-with-known-starting-byte

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!