OneCompiler

Awesome Bitwise Operations and Tricks with Examples

1. Set nth bit of integer x

"Set nth bit of integer x" means to change the value of the n-th bit (counting from 0, starting from the right) in the binary representation of the integer x to 1.

x | (1<<n)

Example


#include <iostream>
using namespace std;

int main() 
{
    int x = 10; // 1010 in binary
    int n = 2;
    int result = x | (1 << n);  // 1110 in binary
    cout << result << endl; // Outputs 14
    return 0;
}

2. Unset nth bit of integer x

"Unset nth bit of integer x" refers to the process of changing the value of the nth bit of the integer x to 0, regardless of its current state (whether it is currently 0 or 1).

x & ~(1<<n)

Example


#include <iostream>  
using namespace std;  

int main() {  
    int x = 10; // 1010 in binary  
    int n = 1;  // Bit position to unset  
    int result = x & ~(1 << n); // Unset the nth bit  
    cout << result << endl; // Output the result (8, which is 1000 in binary)  
    return 0;  
}

3. Toggle nth bit of x

To "toggle the nth bit of x" means to change the state of the nth bit in the binary representation of the integer x. This means if the nth bit is currently 1, it will be changed to 0; if it is currently 0, it will be changed to 1.

x ^ (1<<n)

Example

#include <iostream>
using namespace std;

int main() 
{
    int x = 10; // 1010 in binary
    int n = 0;
    int result = x ^ (1 << n); // Toggle the 0th bit: 1010 ^ 0001 = 1011
    n = 3;
    result = result ^ (1 << n); // Toggle the 3rd bit: 1011 ^ 1000 = 0011
    cout << result << endl; // Output: 3
    return 0;
}

4. Multiply integer x by the nth power of 2

"Multiply integer x by the nth power of 2" means to take the integer value of x and multiply it by 2 raised to the power of n.

x << n

Example

#include <iostream>
using namespace std;

int main() 
{
    int x = 10; // 10 in decimal
    int n = 3;  // Number of positions to shift
    int result = x << n; // Left shift x by n positions: 10 * (2^3) = 80
    cout << result << endl; // Output: 80
    return 0;
}

5. Divide integer x by the nth power of 2

To divide an integer x by the nth power of 2, we are required to compute x divided by 2 raised to the power of n (x / 2^n).

x >> n;

Example

#include <iostream>
using namespace std;

int main() 
{
    int x = 80; // 80 in decimal
    int n = 3;  // Number of positions to shift
    int result = x >> n; // Right shift x by n positions: 80 / (2^3) = 10
    cout << result << endl; // Output: 10
    return 0;
}

6. Check equality of two integer

"Check equality of two integers" refers to the process of determining whether two whole numbers (integers) are the same value.

(num1 ^ num2) == 0; // num1 == num2

Example

#include <iostream>  

using namespace std;  

int main()   
{  
    int num1 = 10;  
    int num2 = 10;  
    if ((num1 ^ num2) == 0)   
        cout << "Equal";  
    else  
        cout << "Not Equal";  
    return 0;  
}