C++ Tutorial C++ Advanced C++ References

C++ - left shift operator assignment



The Bitwise left shift assignment operator (<<=) assigns the first operand a value equal to the result of Bitwise left shift operation of two operands.

(x <<= y) is equivalent to (x = x << y)

The Bitwise left shift operator (<<) takes the two numbers and left shift the bits of first operand by number of place specified by second operand. For example: for left shifting the bits of x by y places, the expression (x<<y) can be used. It is equivalent to multiplying x by 2y.

The example below describes how left shift operator works:

1000 << 2 returns 4000

                      (In Binary)
   1000         ->    1111101000  
   << 2                     |  left shift the bits
   -----                    V  by 2 places
   4000         <-  111110100000 
                      (In Binary) 

The code of using left shift operator (<<) is given below:

#include <iostream>
using namespace std;
 
int main (){
  int x = 1000;

  //left shift assignment operation
  x <<= 2;

  //Displaying the result
  cout<<"x = "<<x;
  return 0;
}

The output of the above code will be:

x = 4000

Example: Count number of 1 Bits in a positive integer

Consider an integer 1000. In the bit-wise format, it can be written as 1111101000. However, all bits are not written here. A complete representation will be 32 bit representation as given below:

00000000000000000000001111101000  

Bitwise AND operation with 1 at any bit results into 1 if the bit is 1 or 0 if the bit is 0. Performing such operation at every bit, and counting the number of 1 gives the count of 1 bits in the given positive integer. To achieve this bitwise left shift assignment operator can be used as shown in the example below:

#include <iostream>
using namespace std;

int CountOneBits(int n) {
  int mask = 1;
  int count = 0;
  
  //performing bitwise AND operation
  //at every bit of the number
  for(int i = 0; i < 32; ++i) { 
    if((mask & n) == mask) 
      count++;
    mask <<= 1;
  }
  return count;
}

int main() {
  cout<<"CountOneBits(1000) = "<<
    CountOneBits(1000)<<"\n";
  cout<<"CountOneBits(1023) = "<<
    CountOneBits(1023)<<"\n";   
  return 0;
}

The above code will give the following output:

CountOneBits(1000) = 6
CountOneBits(1023) = 10

❮ C++ - Operators