# Using the leftshift operator << in c++!

Recently in a test within college I came across the use of the shift operator. We had to work out the answer by hand so I thought I’d do a post about it. I have also written a program to help you understand it.

This was the question I was asked.

What is the value of c after the following?

int a=12
int b=2;

int c=a<<b;

How to work it

Its actually really simple to work out.

The leftshift operator is the equivalent of moving all the bits of a number a specified number of places to the left:

[variable]<<[number of places]

1. Convert the variable to binary.
12 in binary is 1100.

2. Add the number of places onto the number.
This case it is 2 therefore add on 2 0's.

3. The number is now 110000.

4. count the number of 0's.
This case there is 4 0's

5. Now times the variable by the number of 0's.
12*4 in this case = 48.

8. We have now got our answer.

The code to work it out:

```#include <iostream>

using namespace std;

int main()
{
int firstNum, secondNum;

int result;

cout << "Using the shift operator <<!" << endl;

cout << "Indicates the bits are to be shifted to the left." << endl;

cin >> firstNum;

cout << "Please enter you second whole number" << endl;

cin >> secondNum;

result = firstNum << secondNum;

cout << result << endl;

return 0;
}//main

```

## One thought on “Using the leftshift operator << in c++!”

1. gbochev

very, very usefull post !