C#二进制字节流查找函数IndexOf的示例代码详解


本文摘自PHP中文网,作者黄舟,侵删。

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

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

/// <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;

}

使用示例:

1

2

3

4

5

6

7

8

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;

 }

以上就是C#二进制字节流查找函数IndexOf的示例代码详解的详细内容!

相关阅读 >>

C#遍历文件夹子目录下所有图片及遍历文件夹下的文件代码分享

简述C#中builder和buffer类的用法详解

C#高级编程(一)-.net体系结构

C#正则表达式匹配与替换字符串功能示例

C#中常用的正则表达式总结分享

C#控制台应用程序中如何输出彩色字体的详细介绍

.net是否真的被国内市场嫌弃?

详细介绍用C#描述数据结构3:arraylist的图文代码

C#中如何实现带百分比的进度条功能的示例代码分享

C#如何防止sql注入?

更多相关阅读请进入《C#》频道 >>




打赏

取消

感谢您的支持,我会继续努力的!

扫码支持
扫码打赏,您说多少就多少

打开支付宝扫一扫,即可进行扫码打赏哦

分享从这里开始,精彩与您同在

评论

管理员已关闭评论功能...