Counting 8-bits pattern
给一个char* str, 给一个 char pattern, 要求找出8bit pattern在str里出现几次。e.g. str is "13" 就是0000,0001,0000,0011,pattern is 1000,0001 输出结果就
是1次。
int countPattern(char* str, char pattern);
思路:
每次抽出两个字符做bitwise rolling。检查第一个字符是否符合pattern。
题解:
int countPattern2(char c1, char c2, char pattern) { int count = 0; char mask = (1 << 7); int i; for(i = 0; i < 8; ++i) { if (c1 == pattern) ++count; c1 <<= 1; c1 += ((c2 & mask) ? 1 : 0); c2 <<= 1; } return count; } int countPattern(const char* str, char pattern) { const s_length = strlen(str); int i; int count = 0; for(i = 0; i < s_length - 1; ++i) count += countPattern2(str[i], str[i + 1], pattern); if (str[s_length - 1] == pattern) ++count; return count; }