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

黄舟
Release: 2017-03-13 17:45:59
Original
3009 people have browsed it

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

        /// 
        /// 报告指定的 System.Byte[] 在此实例中的第一个匹配项的索引。
        /// 
        /// 被执行查找的 System.Byte[]。
        /// 要查找的 System.Byte[]。
        /// 如果找到该字节数组,则为 searchBytes 的索引位置;如果未找到该字节数组,则为 -1。如果 searchBytes 为 null 或者长度为0,则返回值为 -1。
        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;
        }
Copy after login

使用示例:

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;
 }
Copy after login

The above is the detailed content of C#二进制字节流查找函数IndexOf的示例代码详解. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact [email protected]
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!