Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find First Specific Byte in a Byte[] Array c#

I have a byte array and wish to find the first occurance (if any) of a specific byte.

Can you guys help me with a nice, elegant and efficient way to do it?

 /// Summary
/// Finds the first occurance of a specific byte in a byte array.
/// If not found, returns -1.
public int GetFirstOccurance(byte byteToFind, byte[] byteArray)
{

}
like image 922
divinci Avatar asked Jun 10 '09 10:06

divinci


2 Answers

Array.IndexOf?

like image 67
Greg Beech Avatar answered Oct 02 '22 07:10

Greg Beech


public static int GetFirstOccurance(byte byteToFind, byte[] byteArray)
{
   return Array.IndexOf(byteArray,byteToFind);
}

It will return -1 if not found

Or as Sam pointed out, an extension method:

public static int GetFirstOccurance(this byte[] byteArray, byte byteToFind)
{
   return Array.IndexOf(byteArray,byteToFind);
}

Or to make it generic:

public static int GetFirstOccurance<T>(this T[] array, T element)
{
   return Array.IndexOf(array,element);
}

Then you can just say:

int firstIndex = byteArray.GetFirstOccurance(byteValue);
like image 32
Philippe Leybaert Avatar answered Oct 02 '22 08:10

Philippe Leybaert