基于数组的位运算1 数组位的基本运算

来源:互联网 发布:图片分类展示网站源码 编辑:程序博客网 时间:2024/05/15 23:49

typedef unsigned char uchar;
typedef unsigned short ushort;
typedef unsigned int uint;


//vc ++ 6.0 不支持long long
//linux gcc  不支持__int64
#ifdef _MSC_VER
    typedef __int64 int64;
    typedef unsigned __int64 uint64;
    typedef int64 ltype;
#else
    typedef long long int64;
    typedef unsigned long long uint64;
    typedef uint64 ltype;
#endif

 

//数组类型
# define MOVE  3
# if MOVE == 3
 typedef uchar utype;
# elif MOVE == 4
 typedef ushort utype;
# elif MOVE == 5
 typedef uint utype;
# elif MOVE == 6
 typedef uint64 utype;
# endif


//设置宏, 确保数组a与BITARRAY_TYPE 设置一致
# define MASK_N(n)         (1 << ((n) & MASK))
# define SET_BIT(a, n)     a[(n) >> MOVE] |= MASK_N(n)  //设数组a的第n个bit位1
# define CLR_BIT(a, n)     a[(n) >> MOVE] &= ~MASK_N(n) //设置n为0
# define FLP_BIT(a, n)     a[(n) >> MOVE] ^= MASK_N(n) //测试bit是否为1
# define TST_BIT(a, n)     (a[(n) >> MOVE] & MASK_N(n)) //位反转


//宏可以改成函数形式, 不受数组类型影响
void set_bit(uchar* bitarray, uint pos)
{
    bitarray[pos >> 3] |= (1 << (pos & 7))
}


//或者c++模版形式
template<typename T>
void set_bit(T* bitarray, uint pos)
{
    const int bitmove = sizeof(T) + 2;
    bitarray[pos >> bitmove] |= (1 << ((pos & (1 << bitmove) - 1)));
}