linux bitops


原文链接: linux bitops

bitops.h

GENMASK_ULL 和GENMASK,产生high和low之间全是1的值

GENMASK_ULL(39, 21) 这行执行后的值等于0x000000ffffe00000,
简单说就是将39和21 之间的bit置为1.对应的GENMASK 是产生32 bit的mask

源码如下:
#define GENMASK(h, l)

(((~0UL) << (l)) & (~0UL >> (BITS_PER_LONG - 1 - (h))))

#define GENMASK_ULL(h, l)

(((~0ULL) << (l)) & (~0ULL >> (BITS_PER_LONG_LONG - 1 - (h))))

与之对应的是可以通过下面两个宏,来移位

#define BIT(nr) (1UL << (nr))
#define BIT_ULL(nr) (1ULL << (nr))

#ifdef KERNEL
#define BIT(nr) (1UL << (nr))
#define BIT_ULL(nr) (1ULL << (nr))
#define BIT_MASK(nr) (1UL << ((nr) % BITS_PER_LONG))
#define BIT_WORD(nr) ((nr) / BITS_PER_LONG)
#define BIT_ULL_MASK(nr) (1ULL << ((nr) % BITS_PER_LONG_LONG))
#define BIT_ULL_WORD(nr) ((nr) / BITS_PER_LONG_LONG)
#define BITS_PER_BYTE 8
#define BITS_TO_LONGS(nr) DIV_ROUND_UP(nr, BITS_PER_BYTE * sizeof(long))
#endif

/*

  • Create a contiguous bitmask starting at bit position @l and ending at
  • position @h. For example
  • GENMASK_ULL(39, 21) gives us the 64bit vector 0x000000ffffe00000.
    */
    #define GENMASK(h, l)
    (((~0UL) << (l)) & (~0UL >> (BITS_PER_LONG - 1 - (h))))

#define GENMASK_ULL(h, l)

(((~0ULL) << (l)) & (~0ULL >> (BITS_PER_LONG_LONG - 1 - (h))))

extern unsigned int __sw_hweight8(unsigned int w);
extern unsigned int __sw_hweight16(unsigned int w);
extern unsigned int __sw_hweight32(unsigned int w);
extern unsigned long sw_hweight64(u64 w);

`