位操作方法集合

此文章用于积累bit操作的一些magic方法, 并不断更新。



///< 1. 判断奇偶数

///< return: true is odd , else even

bool isOdd(int x){

    return (x & 1);

}

///< 2.是否为2的指数

bool isPowerOfTwo(int x){

    if((x >> 31)){  ///和0做比较

        return false;

    }

    return (x & (x - 1)) == 0;

}

///< 3.取余

int remainderNumber(int num, int n){

    return num & (n - 1);

}

///< 4.显示二进制

void showBit(long x){

    std::cout << "-----> ";

    std::vector tmp;

    tmp.reserve(10);

    do{

        tmp.push_back(x&1);

        x = x >> 1;

    }while(x);

    for(int i=tmp.size()-1; i>=0; --i){

        if(remainderNumber(i+1, 4) == 0){

            std::cout << " ";

        }

        std::cout << tmp[i];

    }

    std::cout << std::endl;

}

///< 5.两数交换

void swap(int &a, int &b){

    a ^= b;

    b ^= a;

    a ^= b;

}

///< 6.两数是否异号

bool isOppositeSign(int a, int b){

    return (a ^ b) < 0;

}

///< 7.取绝对值

int abs(int a){

    if(!(a >> 31)) //正数

        return a;

    return (~a) + 1;

}

你可能感兴趣的:(位操作方法集合)