这可能是一个稍微理论化的问题.我有一个包含网络数据包的char字节数组.我想检查每66位特定位对(’01’或’10’)的出现.也就是说,一旦找到第一对位,我就必须跳过66位并再次检查是否存在相同的位.我正在尝试用掩码和移位实现一个程序,这有点变得复杂.我想知道是否有人可以提出更好的方法来做同样的事情.
到目前为止我写的代码看起来像这样.但它并不完整.
test_sync_bits(char *rec,int len) { uint8_t target_byte = 0; int offset = 0; int save_offset = 0; uint8_t *pload = (uint8_t*)(rec + 24); uint8_t seed_mask = 0xc0; uint8_t seed_shift = 6; uint8_t value = 0; uint8_t found_sync = 0; const uint8_t sync_bit_spacing = 66; /*hunt for the first '10' or '01' combination.*/ target_byte = *(uint8_t*)(pload + offset); /*Get all combinations of two bits from target byte.*/ while(seed_shift) { value = ((target_byte & seed_mask) >> seed_shift); if((value == 0x01) || (value == 0x10)) { save_offset = offset; found_sync = 1; break; } else { seed_mask = (seed_mask >> 2) ; seed_shift-=2; } } offset = offset + 8; seed_shift = (seed_shift - 4) > 0 ? (seed_shift - 4) : (seed_shift + 8 - 4); seed_mask = (seed_mask >> (6 - seed_shift)); }
我想出的另一个想法是使用下面定义的结构
typedef struct { int remainder_bits; int extra_bits; int extra_byte; }remainder_bits_extra_bits_map_t; static remainder_bits_extra_bits_map_t sync_bit_check [] = { {6,4,0},{5,5,{4,6,{3,7,{2,8,{1,1,1},{0,2,};
我的方法是否正确?任何人都可以建议任何改进吗?
解决方法
查找表的想法
只有256个可能的字节.这足够少,您可以构建一个可以在一个字节中发生的所有可能位组合的查找表.
查找表值可以记录模式的位位置,它还可以具有标记可能的连续开始或连续完成值的特殊值.
编辑:
我认为延续价值会很愚蠢.相反,要检查与字节重叠的模式,将字节与该位的OR从另一个字节移位,或者手动检查每个字节的结束位.也许((bytes [i]& 0x01)&(bytes [i 1]& 0x80))== 0x80和((bytes [i]& 0x01)&(bytes [i 1]& 0x80) )== 0x01对你有用.
你没有这么说我也假设你正在寻找任何字节的第一场比赛.如果您正在寻找每个匹配,然后检查66位的结束模式,这是一个不同的问题.
要创建查找表,我会编写一个程序来为我完成.它可能是您最喜欢的脚本语言,也可能是C语言.程序会编写一个类似于以下内容的文件:
/* each value is the bit position of a possible pattern OR'd with a pattern ID bit. */ /* 0 is no match */ #define P_01 0x00 #define P_10 0x10 const char byte_lookup[256] = { /* 0: 0000_0000,0000_0001,0000_0010,0000_0011 */ 0,2|P_01,3|P_01,/* 4: 0000_0100,0000_0101,0000_0110,0000_0111,*/ 4|P_01,4|P_01,/* 8: 0000_1000,0000_1001,0000_1010,0000_1011,*/ 5|P_01,5|P_01,};
乏味.这就是为什么我会编写一个程序来为我编写它.