Skip to content

一些位运算

cpp
// pos >= 0, from right
static int getBit(int num, int pos) {
    return (num >> pos) & 1;
}

static int getHighestBitOne(int num) {
    int pos = -1;
    while (num > 0) {
        ++pos;
        num >>= 1;
    }
    return pos;
}

static int setBit(int num, int pos, int to) {
    if (to == 1) {
        num |= (1 << pos);
    } else if (to == 0) {
        num &= ~(1 << pos);
    }
    return num;
}


// Example to = 0, num = 0b1001011:
// n = 0 : 1001011
// n = 1 : 1001010
// n = 2 : 1001000
// n = 3 : 1001000
// n = 4 : 1000000
// n = 5 : 1000000
// n = 6 : 1000000
// n = 7 : 0000000
//
// Example to = 1, num = 0b1001011:
// n = 0 : 1001011
// n = 1 : 1001011
// n = 2 : 1001011
// n = 3 : 1001111
// n = 4 : 1001111
// n = 5 : 1011111
// n = 6 : 1111111
// n = 7 : 1111111
static int setNBits(int num, int n, int to) {
    if (to == 1) {
        num |= (1 << n) - 1;
    } else if (to == 0) {
        num &= -(1 << n);
    }
    return num;
}