代码实现:在字节数组中查找16进制字节序列(C#)
近日在工作中需要在字节数组中查找某个16进制字节序列,没找到现成的,只好自己写了一个,不管效率如何,只要自己用着
顺手就好 :)
代码如下:
//在buffer中查找16进制字节序列key,找到返回1,未找到返回0
public int SearchByte(byte[] buffer, byte[] key, int startPos, ref int pos)
{
int i = startPos;
int tem_pos = 0;
bool found1 = false;
int found2 = 0;
do
{
for (int j = 0; j < key.Length; j++)
{
if (buffer[i] == key[j])
{
if (j == 0)
{
found1 = true;
tem_pos = i;
}
else
found2 = 1;
i = i + 1;
}
else
{
if (j == 0)
found1 = false;
else
found2 = 2;
}
if (found1 == false)
{
i = i + 1;
break;
}
if ((found2 == 2))
{
i = i - j + 1;
found1 = false;
found2 = 0;
break;
}
if ((found1 == true) && (found2 == 1) && (j == (key.Length - 1))) //匹配上了
{
pos = i - (key.Length);
return 1;
}
}
}
while (i < buffer.Length);
return 0;
}
用法:
int startPos =0;
int endPos = 0;
byte[] bHead = new byte[3];
bHead[0] = 0xA0;
bHead[1] = 0xA6;
bHead[2] = 0xB8;
if ( 1 == SearchByte(readBuffer, bHead, startPos, ref endPos))
{
//the endPos value 就是bHead在readBuffer中的位置
}