二进制字节流查找函数IndexOf

二进制字节流查找函数IndexOf

C# 二进制字节流查找函数IndexOf

        /// <summary>
/// 报告指定的 System.Byte[] 在此实例中的第一个匹配项的索引。
/// </summary>
/// <param name="srcBytes">被运行查找的 System.Byte[]。</param>
/// <param name="searchBytes">要查找的 System.Byte[]。</param>
/// <returns>假设找到该字节数组。则为 searchBytes 的索引位置。假设未找到该字节数组。则为 -1。假设 searchBytes 为 null 或者长度为0。则返回值为 -1。</returns>
internal int IndexOf(byte[] srcBytes, byte[] searchBytes)
{
if (srcBytes == null) { return -1; }
if (searchBytes == null) { return -1; }
if (srcBytes.Length == 0) { return -1; }
if (searchBytes.Length == 0) { return -1; }
if (srcBytes.Length < searchBytes.Length) { return -1; }
for (int i = 0; i < srcBytes.Length - searchBytes.Length; i++)
{
if (srcBytes[i] == searchBytes[0])
{
if (searchBytes.Length == 1) { return i; }
bool flag = true;
for (int j = 1; j < searchBytes.Length; j++)
{
if (srcBytes[i + j] != searchBytes[j])
{
flag = false;
break;
}
}
if (flag) { return i; }
}
}
return -1;
}

使用演示样例:

receiveData = new byte[1024];
int receiveLen = socket.ReceiveFrom(receiveData, ref ep);
receiveData = this.SubByte(receiveData, 0, receiveLen);
if (this.IndexOf(receiveData, System.Text.Encoding.Unicode.GetBytes("Exec_Exit")) != -1)
{
this.runing = false;
break;
}

05-06 04:47