Bitwise operators are special operators in programming that work directly on binary bits (0 and 1). Since computers store all data in binary form, bitwise operations help us manipulate data at the lowest level using operations like AND, OR, XOR, NOT, and bit shifting.
They are commonly used in optimization, performance-critical code, masking, toggling bits, and low-level programming.
They are used to perform fast calculations and binary manipulation.
They help in setting, clearing, checking, and toggling bits.
Bitwise operations are often faster for low-level and bit-manipulation tasks.
Bitwise operations enable packing multiple flags into a single variable, reducing memory usage.
Bitwise Operators / Basics of Bit manipulation
Bit manipulation works on binary bits (0 and 1) using bitwise operators, making it fast and efficient. These operations are executed by the CPU’s Arithmetic Logic Unit (ALU) and are commonly used for optimization, efficient flag handling, and performance-critical tasks.
The main bitwise operators are:
AND (&)
OR (|)
XOR (^)
NOT (~)
Left Shift (<<)
Right Shift (>>)
Bitwise AND Operator (&)
The bitwise AND operator is denoted using a single ampersand symbol, i.e. &. The & operator takes two equal-length bit patterns as parameters. The two-bit integers are compared. If the bits in the compared positions of the bit patterns are 1, then the resulting bit is 1. If not, it is 0.
Example:
Take two bit values X and Y, where X = 7= (111)2 and Y = 4 = (100)2 . Take Bitwise and of both X & y
The | Operator takes two equivalent length bit designs as boundaries; if the two bits in the looked-at position are 0, the next bit is zero. If not, it is 1.
Example:
Take two bit values X and Y, where X = 7= (111)2 and Y = 4 = (100)2 . Take Bitwise OR of both X, y
Bitwise OR of (7 | 4)
Explanation: On the basis of truth table of bitwise OR operator we can conclude that the result of
1 | 1 = 1 1 | 0 = 1 0 | 1 = 1 0 | 0 = 0
We used the similar concept of bitwise operator that are show in the image.
The ^ operator (also known as the XOR operator) stands for Exclusive Or. Here, if bits in the compared position do not match their resulting bit is 1. i.e, The result of the bitwise XOR operator is 1 if the corresponding bits of two operands are opposite, otherwise 0.
Example:
Take two bit values X and Y, where X = 7= (111)2 and Y = 4 = (100)2 . Take Bitwise and of both X & y
Bitwise OR of (7 ^ 4)
Explanation: On the basis of truth table of bitwise XOR operator we can conclude that the result of
1 ^ 1 = 0 1 ^ 0 = 1 0 ^ 1 = 1 0 ^ 0 = 0
We used the similar concept of bitwise operator that are show in the image.
All the above three bitwise operators are binary operators (i.e, requiring two operands in order to operate). Unlike other bitwise operators, this one requires only one operand to operate.
The bitwise Not Operator takes a single value and returns its one’s complement.
The one’s complement of a binary number is obtained by toggling all bits in it, i.e, transforming the 0 bit to 1 and the 1 bit to 0.
Example:
Take two bit values X and Y, where X = 5= (101)2 . Take Bitwise NOT of X.
Explanation: On the basis of truth table of bitwise NOT operator we can conclude that the result of
~1 = 0 ~0 = 1
We used the similar concept of bitwise operator that are show in the image.
C++
#include<iostream>usingnamespacestd;intmain(){inta=0;cout<<"Value of a without using NOT operator: "<<a;cout<<"\nInverting using NOT operator (with sign bit): "<<(~a);cout<<"\nInverting using NOT operator (without sign bit): "<<(!a);return0;}
Java
importjava.io.*;classGFG{publicstaticvoidmain(String[]args){inta=0;System.out.println("Value of a without using NOT operator: "+a);System.out.println("Inverting using NOT operator (with sign bit): "+(~a));if(a!=1)System.out.println("Inverting using NOT operator (without sign bit): 1");elseSystem.out.println("Inverting using NOT operator (without sign bit): 0");}}
Python
a=0print("Value of a without using NOT operator: ",a)print("Inverting using NOT operator (with sign bit): ",(~a))print("Inverting using NOT operator (without sign bit): ",int(not(a)))
C#
usingSystem;publicclassGFG{staticpublicvoidMain(){inta=0;Console.WriteLine("Value of a without using NOT operator: "+a);Console.WriteLine("Inverting using NOT operator (with sign bit): "+(~a));if(a!=1)Console.WriteLine("Inverting using NOT operator (without sign bit): 1");elseConsole.WriteLine("Inverting using NOT operator (without sign bit): 0");}}
JavaScript
leta=0;console.log("Value of a without using NOT operator: "+a);console.log("Inverting using NOT operator (with sign bit): "+(~a));if(!a)console.log("Inverting using NOT operator (without sign bit): 1");elseconsole.log("Inverting using NOT operator (without sign bit): 0");
Output
Value of a without using NOT operator: 0
Inverting using NOT operator (with sign bit): -1
Inverting using NOT operator (without sign bit): 1
Left-Shift (<<)
The left shift operator is denoted by the double left arrow key (<<). The general syntax for left shift is shift-expression << k. The left-shift operator causes the bits in shift expression to be shifted to the left by the number of positions specified by k. The bit positions that the shift operation has vacated are zero-filled.
Note: Every time we shift a number towards the left by 1 bit it multiply that number by 2.
Example:
Input: Left shift of 5 by 1. Binary representation of 5 = 00101 and Left shift of 001012 by 1 (i.e, 00101 << 1)
Left shift of 5 by 1
Output: 10 Explanation: All bit of 5 will be shifted by 1 to left side and this result in 010102, Which is equivalent to 10
Input: Left shift of 5 by 2. Binary representation of 5 = 00101 and Left shift of 001012 by 1 (i.e, 00101 << 2)
Left shift of 5 by 2
Output: 20 Explanation: All bit of 5 will be shifted by 1 to left side and this result in 101002, Which is equivalent to 20
Input: Left shift of 5 by 3. Binary representation of 5 = 00101 and Left shift of 001012 by 1 (i.e, 00101 << 3)
Left shift of 5 by 3
Output: 40 Explanation: All bit of 5 will be shifted by 1 to left side and this result in 010002, Which is equivalent to 40
# Python code for the above approachnum1=1024bt1=bin(num1)[2:].zfill(32)print(bt1)num2=num1<<1bt2=bin(num2)[2:].zfill(32)print(bt2)num3=num1<<2bitset13=bin(num3)[2:].zfill(16)print(bitset13)
// JavaScript code for the above approachletnum1=1024;letbt1=num1.toString(2).padStart(32,'0');console.log(bt1);letnum2=num1<<1;letbt2=num2.toString(2).padStart(32,'0');console.log(bt2);letnum3=num1<<2;letbitset13=num3.toString(2).padStart(16,'0');console.log(bitset13);
The right shift operator is denoted by the double right arrow key (>>). The general syntax for the right shift is "shift-expression >> k". The right-shift operator causes the bits in shift expression to be shifted to the right by the number of positions specified by k. For unsigned numbers, the bit positions that the shift operation has vacated are zero-filled. For signed numbers, the sign bit is used to fill the vacated bit positions. In other words, if the number is positive, 0 is used, and if the number is negative, 1 is used.
Note: Every time we shift a number towards the right by 1 bit it divides that number by 2.
Example:
Input: Right shift of 5 by 1. Binary representation of 5 = 00101 and Right shift of 00101 by 1 (i.e, 00101 >> 1)
Right shift of 5 by 1
Output: 2 Explanation: All bit of 5 will be shifted by 1 to Rightside and this result in 00010Which is equivalent to 2
Input: Right shift of 5 by 2. Binary representation of 5 = 00101 and Right shift of 00101 by 2 (i.e, 00101 >> 2)
Right shift of 5 by 2
Output: 1 Explanation: All bit of 5 will be shifted by 2 to Right side and this result in 00001, Which is equivalent to 1
Input: Right shift of 5 by 3. Binary representation of 5 = 00101 and Right shift of 00101 by 3 (i.e, 00101 >> 3)
Right shift of 5 by 3
Output: 0 Explanation: All bit of 5 will be shifted by 3 to Right side and this result in 00000, Which is equivalent to 0
// JavaScript code for the above approachletnum1=1024;letbt1=num1.toString(2).padStart(32,'0');console.log(bt1);letnum2=num1>>1;letbt2=num2.toString(2).padStart(32,'0');console.log(bt2);letnum3=num1>>2;letbitset13=num3.toString(2).padStart(16,'0');console.log(bitset13);
Bit operations are used for the optimization of embedded systems.
The Exclusive-or operator can be used to confirm the integrity of a file, making sure it has not been corrupted, especially after it has been in transit.
Bitwise operations are used in Data encryption and compression.
Bits are used in the area of networking, framing the packets of numerous bits which are sent to another system generally through any type of serial interface.
Digital Image Processors use bitwise operations to enhance image pixels and to extract different sections of a microscopic image.
Practice Problems on Bitwise Algorithm
Solve these questions to improve your understanding of bitwise operators and bit manipulation techniques.
Note: All the above Bitwise Practice Problems are optimized and run in O(1) Time Complexity with O(1) Auxiliary Space.
1. Set a bit in the number
If we want to set a bit at nth position in the number 'num', it can be done using the 'OR' operator( | ).
First, we left shift 1 to n position via (1<<n).
Then, use the "OR" operator to set the bit at that position. "OR" operator is used because it will set the bit even if the bit is unset previously in the binary representation of the number 'num'.
Note: If the bit would be already set then it would remain unchanged.
C++
#include<iostream>usingnamespacestd;// num is the number and pos is the position// at which we want to set the bit.voidSet(int&num,intpos){// First step is shift '1', second// step is bitwise ORnum|=(1<<pos);}intmain(){intnum=4,pos=1;Set(num,pos);cout<<num<<endl;return0;}
Java
importjava.io.*;classGFG{publicstaticvoidmain(String[]args){intnum=4,pos=1;num=set(num,pos);System.out.println(num);}publicstaticintset(intnum,intpos){// First step is shift '1', second// step is bitwise ORnum|=(1<<pos);returnnum;}}
Python
# num = number, pos = position at which we want to set the bitdefset(num,pos):# First step = Shift '1'# Second step = Bitwise ORnum|=(1<<pos)print(num)num,pos=4,1set(num,pos)
C#
usingSystem;publicclassGFG{staticpublicvoidMain(){intnum=4,pos=1;set(num,pos);}// num = number, pos = position at which we want to set// the bitstaticpublicvoidset(intnum,intpos){// First Step: Shift '1'// Second Step: Bitwise ORnum|=(1<<pos);Console.WriteLine(num);}}
JavaScript
// num is the number and pos is the position // at which we want to set the bit.functionset(num,pos){// First step is shift '1', second// step is bitwise ORnum|=(1<<pos);console.log(parseInt(num));}letnum=4;letpos=1;set(num,pos);
Output
6
2. unset/clear a bit at n'th position in the number
Suppose we want to unset a bit at nth position in number 'num' then we have to do this with the help of "AND" (&) operator.
First, we left shift '1' to n position via (1<<n) then we use bitwise NOT operator '~' to unset this shifted '1'.
Now after clearing this left shifted '1' i.e making it to '0' we will 'AND'(&) with the number 'num' that will unset bit at nth position.
C++
#include<iostream>usingnamespacestd;// First step is to get a number that has all 1's except// the given position.voidunset(int&num,intpos){// Second step is to bitwise and this number with given// numbernum&=(~(1<<pos));}intmain(){intnum=7;intpos=1;unset(num,pos);cout<<num<<endl;return0;}
Java
/*package whatever //do not write package name here */importjava.io.*;classGFG{publicstaticvoidmain(String[]args){intnum=7,pos=1;num=unset(num,pos);System.out.println(num);}publicstaticintunset(intnum,intpos){// Second step is to bitwise and this number with// given numbernum=num&(~(1<<pos));returnnum;}}
Python
# First Step: Getting which have all '1's except the# given positiondefunset(num,pos):# Second Step: Bitwise AND this number with the given numbernum&=(~(1<<pos))print(num)num,pos=7,1unset(num,pos)
C#
usingSystem;publicclassGFG{staticpublicvoidMain(){// First Step: Getting a number which have all '1's// except the given positionintnum=7,pos=1;unset(num,pos);}staticpublicvoidunset(intnum,intpos){// Second Step: Bitwise AND this number with the// given numbernum&=(~(1<<pos));Console.WriteLine(num);}}
JavaScript
// First step is to get a number that has all 1's except// the given position.functionunset(num,pos){// Second step is to bitwise and this number with given// numberreturnnum&=(~(1<<pos));}letnum=7;letpos=1;console.log(unset(num,pos));
Output
5
3. Toggling a bit at nth position
Toggling means to turn bit 'on'(1) if it was 'off'(0) and to turn 'off'(0) if it was 'on'(1) previously. We will be using the 'XOR' operator here which is this '^'. The reason behind the 'XOR' operator is because of its properties.
Properties of 'XOR' operator.
1^1 = 0
0^0 = 0
1^0 = 1
0^1 = 1
If two bits are different then the 'XOR' operator returns a set bit(1) else it returns an unset bit(0).
C++
#include<iostream>usingnamespacestd;// First step is to shift 1,Second step is to XOR with given// numbervoidtoggle(int&num,intpos){num^=(1<<pos);}intmain(){intnum=4;intpos=1;toggle(num,pos);cout<<num<<endl;return0;}
Java
importjava.io.*;classGFG{publicstaticvoidmain(String[]args){intnum=4,pos=1;num=toggle(num,pos);System.out.println(num);}publicstaticinttoggle(intnum,intpos){// First step is to shift 1,Second step is to XOR// with given numbernum^=(1<<pos);returnnum;}}
Python
deftoggle(num,pos):# First Step: Shifts '1'# Second Step: XOR numnum^=(1<<pos)print(num)num,pos=4,1toggle(num,pos)
C#
usingSystem;publicclassGFG{staticpublicvoidMain(){intnum=4,pos=1;toggle(num,pos);}staticpublicvoidtoggle(intnum,intpos){// First Step: Shift '1'// Second Step: XOR numnum^=(1<<pos);Console.WriteLine(num);}}
JavaScript
// First step is to shift 1,Second step is to XOR with given// numberfunctiontoggle(num,pos){// First Step: Shifts '1'// Second Step: XOR numnum^=(1<<pos)console.log(num)}letnum=4;letpos=1;toggle(num,pos);
Output
6
4. Checking if the bit at nth position is Set or Unset
We used the left shift (<<) operation on 1 to shift the bits to nth position and then use the & operation with number given number, and check if it is not-equals to 0.
// Javascript program for the above approachvarnum=12;varans=num>>1;console.log(ans);
Output
6
7. Compute XOR from 1 to n (direct method)
The problem Compute XOR from 1 to n can be solved based on the following observations: n%4==0->n, 1->1, 2->n+1, 3-0.
Say x = n % 4. The XOR value depends on the value if x.
If, x = 0, then the answer is n. x = 1, then answer is 1. x = 2, then answer is n+1. x = 3, then answer is 0.
C++
#include<iostream>usingnamespacestd;// Direct XOR of all numbers from 1 to nintcomputeXOR(intn){if(n%4==0)returnn;if(n%4==1)return1;if(n%4==2)returnn+1;return0;}intmain(){intn=5;cout<<computeXOR(n)<<endl;return0;}
Java
importjava.io.*;classGFG{// Direct XOR of all numbers from 1 to npublicstaticintcomputeXOR(intn){if(n%4==0)returnn;if(n%4==1)return1;if(n%4==2)returnn+1;return0;}publicstaticvoidmain(String[]args){intn=5;System.out.println(computeXOR(n));}}
usingSystem;publicclassGFG{// Direct XOR of all numbers from 1 to npublicstaticintcomputeXOR(intn){if(n%4==0)returnn;if(n%4==1)return1;if(n%4==2)returnn+1;return0;}publicstaticvoidMain(){intn=5;Console.WriteLine(computeXOR(n));}}
JavaScript
// Direct XOR of all numbers from 1 to nfunctioncomputeXOR(n){if(n%4===0)returnn;if(n%4===1)return1;if(n%4===2)returnn+1;return0;}console.log(computeXOR(5));
8. How to know if a number is a power of 2?
This can be solved based on the following fact:
If a number N is a power of 2, then the bitwise AND of N and N-1 will be 0. But this will not work if N is 0. So just check these two conditions, if any of these two conditions is true.
C++
#include<iostream>usingnamespacestd;// Function to check if x is power of 2boolisPowerOfTwo(intx){// First x in the below expression is// for the case when x is 0returnx&&(!(x&(x-1)));}intmain(){cout<<isPowerOfTwo(2);return0;}
Java
publicclassMain{// Function to check if x is power of 2publicstaticbooleanisPowerOfTwo(intx){returnx!=0&&((x&(x-1))==0);}publicstaticvoidmain(String[]args){System.out.println(isPowerOfTwo(2));}}
Python
# Function to check if x is power of 2defisPowerOfTwo(x):returnxand(not(x&(x-1)))print(isPowerOfTwo(2))
C#
usingSystem;publicclassGFG{// Function to check if x is power of 2staticpublicboolisPowerOfTwo(intx){return(x!=0)&&((x&(x-1))==0);}staticpublicvoidMain(){Console.WriteLine(isPowerOfTwo(2));}}
JavaScript
// Function to check if x is power of 2functionisPowerOfTwo(x){// First x in the below expression is// for the case when x is 0returnx&&(!(x&(x-1)));}console.log(isPowerOfTwo(2));
9. Count Set bits in an integer
Counting set bits means, counting total number of 1’s in the binary representation of an integer. For this problem we go through all the bits of given number and check whether it is set or not by performing AND operation (with 1).
C++
#include<iostream>usingnamespacestd;// Function to calculate the number of set bitsintcountBits(intn){intcount=0;while(n){count+=(n&1);n>>=1;}returncount;}intmain(){intn=5;cout<<countBits(n)<<endl;return0;}
Java
publicclassMain{// Function to calculate the number of set bitspublicstaticintcountBits(intn){intcount=0;while(n>0){count+=(n&1);n>>=1;}returncount;}publicstaticvoidmain(String[]args){System.out.println(countBits(5));// Output: 2}}
usingSystem;publicclassGFG{// Function to calculate the number of set bitspublicstaticintcountBits(intn){intcount=0;while(n>0){count+=(n&1);n>>=1;}returncount;}staticpublicvoidMain(){Console.WriteLine(countBits(5));// Output: 2}}
JavaScript
// Function to calculate the number of set bitsfunctioncountBits(n){letcount=0;while(n>0){count+=(n&1);n>>=1;}returncount;}console.log(countBits(5));
10. Position of rightmost set bit
The idea is to unset the rightmost bit of number n and XOR the result with n. Then the rightmost set bit in n will be the position of the only set bit in the result. Note that if n is odd, we can directly return 1 as the first bit is always set for odd numbers.
Example: The number 20 in binary is 00010100, and the position of the rightmost set bit is 3.
00010100 & (n = 20) 00010011 (n-1 = 19) ------------------- 00010000 ^ (XOR result number with n) 00010100 ------------------- 00000100 -------> rightmost set bit will tell us the position
C++
#include<iostream>usingnamespacestd;// Returns the position of the rightmost set bit of n (1-based)intpositionOfRightmostSetBit(intn){if(n==0)return0;// no set bit// if number is odd, rightmost set bit is at position 1if(n&1)return1;// keep only the rightmost set bitn=n^(n&(n-1));intpos=0;while(n){n>>=1;pos++;}returnpos;}intmain(){intn=18;cout<<positionOfRightmostSetBit(n)<<endl;return0;}
Java
publicclassMain{// Returns the position of the rightmost set bit of n (1-based)publicstaticintpositionOfRightmostSetBit(intn){if(n==0)return0;// no set bit// if the number is odd, return 1if((n&1)!=0)return1;// keep only the rightmost set bitn=n^(n&(n-1));intpos=0;while(n!=0){n>>=1;pos++;}returnpos;}publicstaticvoidmain(String[]args){System.out.println(positionOfRightmostSetBit(18));// Output: 2}}
Python
# Returns the position of the rightmost set bit of n (1-based)defpositionOfRightmostSetBit(n):ifn==0:return0ifn&1:return1# keep only the rightmost set bitn=n^(n&(n-1))pos=0whilen:n>>=1pos+=1returnpos# Driver coden=18print(positionOfRightmostSetBit(n))
C#
usingSystem;publicclassGFG{// Returns the position of the rightmost set bit of n (1-based)publicstaticintpositionOfRightmostSetBit(intn){if(n==0)return0;// no set bit// if the number is odd, return 1if((n&1)!=0)return1;// keep only the rightmost set bitn=n^(n&(n-1));intpos=0;while(n!=0){n>>=1;pos++;}returnpos;}publicstaticvoidMain(){Console.WriteLine(positionOfRightmostSetBit(18));}}
JavaScript
// Returns the position of the rightmost set bit of n (1-based)functionpositionOfRightmostSetBit(n){if(n===0)return0;// no set bit// if the number is odd, return 1if(n&1)return1;// keep only the rightmost set bitn=n^(n&(n-1));letpos=0;while(n){n>>=1;pos++;}returnpos;}console.log(positionOfRightmostSetBit(18));