Friday, January 13, 2023

BITWISE Operators

Setting a bit: To set a specific bit in a number to 1, you can use the bitwise OR operator (|) with a value that has only that bit set. For example, to set the 3rd bit of a number to 1:

num = num | (1 << 3);

Clearing a bit: To clear a specific bit in a number (set it to 0), you can use the bitwise AND operator (&) with a value that has all bits set except for the target bit. For example, to clear the 2nd bit of a number:

num = num & ~(1 << 2);

Toggling a bit: To toggle (flip) a specific bit in a number, you can use the bitwise XOR operator (^) with a value that has only that bit set. For example, to toggle the 4th bit of a number:

num = num ^ (1 << 4);

Checking a bit: To check if a specific bit in a number is set, you can use the bitwise AND operator (&) with a value that has only that bit set. If the result is not zero, then the bit is set. For example, to check if the 5th bit of a number is set:

if ((num & (1 << 5)) != 0) {

    // 5th bit is set

} else {

    // 5th bit is not set

}

Counting set bits: To count the number of bits set to 1 in a number, you can use the trick called "Brian Kernighan's Algorithm" which is an efficient way of counting set bits in a number, It basically flips the last set bit of the number to 0 and count the times you have to do it to reach 0.

int countOnes(uint n) {

    int count = 0;

    while (n > 0) {

        n &= (n-1);

        count++;

    }

    return count;

}

Get the least significant bit: To get the least significant bit (LSB) of a number, you can use the bitwise AND operator (&) with the number 1. For example, to get the LSB of a number:

int lsb = num & 1;

No comments:

Post a Comment