# 2019q1W7上:方鈺學 contributed <`JulianATA`> >有時間會回頭補詳細解釋! >[name=Julian Fang] > 好啊,我等你 > [name=jserv] ## 測驗 `1` : ### `find_next_bit()` : ``` clike static inline size_t find_next_bit(const unsigned long *bitmap, size_t bits, size_t start) { unsigned long t; size_t l = BITS_TO_LONGS(bits); size_t first_long = start / BITS_PER_LONG; size_t long_lower = start - (start % BITS_PER_LONG); if (start >= bits) return bits; t = bitmap[first_long] & BITMAP_FIRST_WORD_MASK(start); for (size_t i = first_long + 1; !t && i < l; i++) { long_lower += BITS_PER_LONG; t = bitmap[i]; t ^= 0UL; } if (!t) return bits; size_t pos = long_lower + bitops_ffs(t) - 1; if(pos >= bits) return bits; return pos; } ``` ## 測驗 `2` : ### `main` : ```clike int main(void) { // sequential check for (int i = 1; i < MAX_TEST_BITS; i++) { bitmap_fill(test, i); assert(find_next_bit(test, i, 0) == 0); bitmap_zero(test, i); assert(find_next_bit(test, i, 0) == i); } // random check srand(time(NULL)); int _t; for (int i = 1; i < 1000; i++){ _t = rand()%MAX_TEST_BITS; bitmap_fill(test,_t); assert(find_next_bit(test, _t, 0) == 0); bitmap_zero(test, _t); assert(find_next_bit(test, _t, 0) == _t); } return 0; } ``` ## 測驗 `3` : ### `bitsops_ffs()` : ```clike static inline size_t bitops_ffs(unsigned long x) { return log2(x & -x) +1; } ``` ## 測驗 `4` : ### `bitsops_ffz()` : ```clike #include <math.h> #include <stdio.h> /** * bitops_ffz() - find (least significant) first zero bit plus one * @x: unsigned long to check * * Return: plus-one index of first zero bit; zero when x is ULONG_MAX */ static inline size_t bitops_ffz(unsigned long x) { return log((-x & (x+1)))+1; } int main() { unsigned long n = 31; printf("%zu", bitops_ffz(n)); return 0; } ``` :::warning 為何需要用到 `log` 呢? ::: ###### tags: `Cprogramming` `LinuxKernel`