noend
Joined: 08 Sep 2008 Posts: 1
|
Help searching a byte pattern within an array of bytes. |
Posted: Mon Sep 22, 2008 6:48 am |
|
|
I am in need to find a byte pattern within an array of bytes. I am treating
the byte array as an array of bits so the pattern may be or may not be
found within two bytes and at any bit position. Then I need to reassemble
those 8 bits into a byte and output them accordingly via RS232.
What I have wrote to resolve this puzzle is:
Code: |
#include <16F877.h>
#device *=16,icd=true
#fuses HS,NOLVP,NOWDT,NOPROTECT
#use delay(clock=20000000)
#use rs232(baud=9600, xmit=PIN_C6, rcv=PIN_C7)
void main()
{
//char table[40]={0x18,0x20,0x10,0x60,0x48,0x10,0xC0,0xD8,0xD0,0x20,0x90,0x18,0x10,0x50,0x38,0xC8,0xC8,0xC8,0x98,0xA8,0x08,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00};
char table[40]={0x68,0x08,0x80,0x08,0x80,0x98,0x08,0x10,0x08,0xB0,0x20,0x08,0xE0,0x68,0x68,0x10,0xC8,0x08,0x08,0xA8,0x98,0xE0,0xE0,0xE0,0xC8,0xD0,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00};
int CurrentBit;
int BitPattern;
int Index;
int TempCurrentBit;
char TempByte;
int x;
int y;
BitPattern=0b11010000; //start sentinel pattern while backwards reading
Index=39;
TempCurrentBit=3;
CurrentBit=3;
TempByte=0;
while(index!=0)
{
if(table[index]!=0)
{
if(bit_test(table[Index],CurrentBit))
{
bit_set(TempByte,TempCurrentBit);
}
++CurrentBit;
++TempCurrentBit;
if(CurrentBit==8)
{
CurrentBit=3;
--Index;
}
if(TempCurrentBit==8)
{
if(TempByte==BitPattern)
{
++Index;
break;
}
if(CurrentBit==7)
{
CurrentBit=3;
}
else
{
++CurrentBit;
++Index;
}
TempCurrentBit=3;
TempByte=0;
}
}
else
{
--Index;
}
}
printf("\r\nthe pattern was found at bit %d and index %d\r\n",CurrentBit,Index);
TempByte=0;
TempCurrentBit=4;
x=Index;
y=CurrentBit;
while(x!=255)
{
if(bit_test(table[x],y))
{
bit_set(TempByte,TempCurrentBit);
}
--TempCurrentBit;
if(TempCurrentBit==255)
{
bit_clear(TempByte,4);
TempByte += 0x30;
putc(TempByte);
TempCurrentBit=4;
TempByte=0;
}
++y;
if(y==8)
{
--x;
y=3;
}
}
} |
Any ideas on how may I optimize my code or even make it better?? |
|