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

转载连接: https://blog.csdn.net/testcs_dn/article/details/25276333


  1. /// <summary>  
  2. /// 报告指定的 System.Byte[] 在此实例中的第一个匹配项的索引。  
  3. /// </summary>  
  4. /// <param name="srcBytes">被执行查找的 System.Byte[]。</param>  
  5. /// <param name="searchBytes">要查找的 System.Byte[]。</param>  
  6. /// <returns>如果找到该字节数组,则为 searchBytes 的索引位置;如果未找到该字节数组,则为 -1。如果 searchBytes 为 null 或者长度为0,则返回值为 -1。</returns>  
  7. internal int IndexOf(byte[] srcBytes, byte[] searchBytes)  
  8. {  
  9.     if (srcBytes == null) { return -1; }  
  10.     if (searchBytes == null) { return -1; }  
  11.     if (srcBytes.Length == 0) { return -1; }  
  12.     if (searchBytes.Length == 0) { return -1; }  
  13.     if (srcBytes.Length < searchBytes.Length) { return -1; }  
  14.     for (int i = 0; i < srcBytes.Length - searchBytes.Length; i++)  
  15.     {  
  16.         if (srcBytes[i] == searchBytes[0])  
  17.         {  
  18.             if (searchBytes.Length == 1) { return i; }  
  19.             bool flag = true;  
  20.             for (int j = 1; j < searchBytes.Length; j++)  
  21.             {  
  22.                 if (srcBytes[i + j] != searchBytes[j])  
  23.                 {  
  24.                     flag = false;  
  25.                     break;  
  26.                 }  
  27.             }  
  28.             if (flag) { return i; }  
  29.         }  
  30.     }  
  31.     return -1;  
  32. }  
使用示例:
[csharp]  view plain  copy
  1. receiveData = new byte[1024];  
  2. int receiveLen = socket.ReceiveFrom(receiveData, ref ep);  
  3. receiveData = this.SubByte(receiveData, 0, receiveLen);  
  4.  if (this.IndexOf(receiveData, System.Text.Encoding.Unicode.GetBytes("Exec_Exit")) != -1)  
  5. {  
  6.     this.runing = false;  
  7.     break;  
  8.  }  

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值