[問題] 徵求bit compare作法?
開發平台(Platform): (Ex: VC++, GCC, Linux, ...)
在微處理機上的C
typedef unsigned char U8;
typedef unsigned int U16;
U8 buf1[32];//每次收到的data,最大長度32 Byte
U8 buf2[32];//pattern,最大長度32 Byte
buf2內容是預先存入的,例如
buf2[0]~buf2[5]=0x36, 0xf0, 0x77, 0x0f, 0x7f,
00110110,11110000,01110111,00001111,10101010,01111111,...
//bit0~7,bit8~15, bit16~23,bit24~31,bit32~39,bit40~47,...
然後buf1收資料進來了,長得可能像這樣
buf1[0]~buf1[6]=0x9b, 0x0d, 0xfc, 0xdd, 0x83, 0xea, 0xd7,...
10011011,00001101,11111100,11011101,10000011,11101010,11010111,...
//bit0~7,bit8~15, bit16~23,bit24~31,bit32~39,bit40~47,bit48~55,...
設定StartBit=6, BitLength=43
也就是從buf1的bit6與buf2的bit0開始比較,共比較43個bit(到buf1的bit48與
buf2的bit42為止),
若完全相同則為true, 只要一個bit不同就為false
以上的例子是true的情況
status=BitCmp(buf1, buf2, StartBit, BitLength);// call function BitCmp
U8 BitCmp(U8 *ptr1, U8 *ptr2, U16 Sbit, U16 Len)
{
U8 temp;
U16 len, bitmod, i, *ptr3;
if(Len+Sbit > 32*8) return 0;
i=Sbit/8;
bitmod=Sbit%8;
len=Len;
while(i--) ptr1++;
for(i=0; i<Len/8; i++)
{
ptr3=(U16*)(ptr1+i);
//temp=(*(ptr1+i))>>bitmod + (*(ptr1+i+1))<<(8-bitmod);
temp=(U8)((*ptr3)>>bitmod);
if(temp!=*ptr2++) return 0;//false
len-=8;
}
if(len)
{
len=0x00ff>>(8-len);
//temp=(*(ptr1+i))>>bitmod + (*(ptr1+i+1))<<(8-bitmod);
//temp&=(U8)len;
ptr3=(U16*)(ptr1+i);
temp=(U8)(((*ptr3)>>bitmod)&len);
if(temp!=((*ptr2)&(U8)len)) return 0;//false
}
return 1;//true
}
因為在微處理器上嘛!
希望這個bit compare的處理可以佔用時間越少越好...
想知道有沒有更快更smart的寫法? 或者有ANSI C的內建函數可利用?
謝謝~
--
※ 發信站: 批踢踢實業坊(ptt.cc)
◆ From: 61.247.173.226
※ 編輯: WillyLin 來自: 61.247.173.226 (08/16 13:15)
→
08/16 13:18, , 1F
08/16 13:18, 1F
支援啊^^
我本來也想用memcmp
但想到用memcmp之前要先把buf1 shift copy到另一個新的buffer
(然後再豪邁的call memcmp一口氣比完...)
這個shift copy的過程其實就已經和上面compare差不多
且長度未必是8的倍數
最後留下的幾個bit 還是要自己處理
※ 編輯: WillyLin 來自: 61.247.173.226 (08/16 13:28)
→
08/16 13:32, , 2F
08/16 13:32, 2F
→
08/16 13:34, , 3F
08/16 13:34, 3F
→
08/16 13:35, , 4F
08/16 13:35, 4F
推
08/16 13:35, , 5F
08/16 13:35, 5F
→
08/16 13:35, , 6F
08/16 13:35, 6F
→
08/16 13:36, , 7F
08/16 13:36, 7F
→
08/16 13:40, , 8F
08/16 13:40, 8F
推
08/16 14:38, , 9F
08/16 14:38, 9F
→
08/16 14:38, , 10F
08/16 14:38, 10F
→
08/16 14:40, , 11F
08/16 14:40, 11F
推
08/16 15:38, , 12F
08/16 15:38, 12F
→
08/16 15:47, , 13F
08/16 15:47, 13F
→
08/16 18:49, , 14F
08/16 18:49, 14F
討論串 (同標題文章)
以下文章回應了本文:
完整討論串 (本文為第 1 之 2 篇):