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)
{
}
Array.IndexOf?
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With