test_bit(置位判断函数)的几种实现方法

方法一

static inline int test_bit(int nr, const volatile void * addr)
{
        return (1UL & (((const int *) addr)[nr >> 5] >> (nr & 31))) != 0UL;
}

方法二

#include <asm/types.h>
static
__always_inline int test_bit2(unsigned int nr, const unsigned long *addr) { return ((1UL << (nr % __BITS_PER_LONG)) & (((unsigned long *)addr)[nr / __BITS_PER_LONG])) != 0; }

方法三

static inline int test_bit3(unsigned int nr, const volatile unsigned long *addr)
{
        unsigned long mask;
addr
+= nr >> 5; mask = 1UL << (nr & 0x1f); return ((mask & *addr) != 0); }

测试代码

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

        //int retval = test_bit(tbit, &value);
        //int retval = test_bit2(tbit, (unsigned long *)&value);
        int retval = test_bit3(tbit, (unsigned long *)&value);
        if (retval)
                printf("bit-%d is set\n", tbit);
        else
                printf("bit-%d is not set\n", tbit);

        return 0;
}

测试结果

 

posted @ 2023-01-30 11:49  闹闹爸爸  阅读(863)  评论(0编辑  收藏  举报