Linux内核中的位操作:ffs.h,fls.h

  • Post author:
  • Post category:linux

今天阅读源码时遇到一个函数:ffs,它时内核中实现的位操作函数,用来查找二进制表示数中第一个为1的位。与ffs对应的还有fls.h,用来查找二进制数中最后一个为1的位。

例如:整数32,对应的二进制为100000,即第一个和最后一个为1的位是6;

          整数34,对应的二进制为100010,第一个为1的位为2,最后一个为1的为是6。

此处给出ffs.h的代码,如下:

#ifndef _ASM_GENERIC_BITOPS_FFS_H_
#define _ASM_GENERIC_BITOPS_FFS_H_

/**
 * ffs - find first bit set
 * @x: the word to search
 *
 * This is defined the same way as
 * the libc and compiler builtin ffs routines, therefore
 * differs in spirit from the above ffz (man ffs).
 */
static inline int ffs(int x)
{
	int r = 1;

	if (!x)
		return 0;
	if (!(x & 0xffff)) {
		x >>= 16;
		r += 16;
	}
	if (!(x & 0xff)) {
		x >>= 8;
		r += 8;
	}
	if (!(x & 0xf)) {
		x >>= 4;
		r += 4;
	}
	if (!(x & 3)) {
		x >>= 2;
		r += 2;
	}
	if (!(x & 1)) {
		x >>= 1;
		r += 1;
	}
	return r;
}

#endif /* _ASM_GENERIC_BITOPS_FFS_H_ */

实验程序如下,执行程序时,带上一个整数,打印第一个为1,和最后一个位为1的位号。

#include "ffs.h"
#include "fls.h"
#include <stdlib.h>
#include <stdio.h>

int main(int argc, char** argv){
    int bit = atoi(argv[1]);

    int fret = -1;
    int lret = -1;

    fret = ffs(bit);
    lret = fls(bit);

    printf("%d the first bit set is: %d\n", bit, fret);
    printf("%d the last bit set is: %d\n", bit, lret);

}

实验结果:


版权声明:本文为calmjiao原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。