Open In App

Left Shift and Right Shift Operators in C/C++

Last Updated : 24 Jun, 2024
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

In C/C++, left shift (<<) and right shift (>>) operators are binary bitwise operators that are used to shift the bits either left or right of the first operand by the number of positions specified by the second operand allowing efficient data manipulation. In this article, we will learn about the left shift and right shift operators.

Left Shift (<<) Operators

The left shift(<<) is a binary operator that takes two numbers, left shifts the bits of the first operand, and the second operand decides the number of places to shift. In other words, left-shifting an integer “a” with an integer “b” denoted as ‘(a<<b)’ is equivalent to multiplying a with 2^b (2 raised to power b). 

Syntax

a << b;

where,

  • a is the integer value to be shifted.
  • b specifies how many positions to shift the bits.

Example: Let’s take a=5; which is 101 in Binary Form. Now, if “a is left-shifted by 2” i.e a=a<<2 then a will become a=a*(2^2). Thus, a=5*(2^2)=20 which can be written as 10100.

Left-Shift-in-c-cpp

Example of Left Shift Operator

C++
// C++ Program to demonstrate use
// of left shift  operator
#include <iostream>
using namespace std;

// Driver code
int main()
{
    // a = 5(00000101), b = 9(00001001)
    unsigned char a = 5, b = 9;

    // The result is 00001010
    cout << "a<<1 = " << (a << 1) << endl;

    // The result is 00010010
    cout << "b<<1 = " << (b << 1) << endl;
    return 0;
}
C
// C Program to demonstrate use
// of left shift  operator
#include <stdio.h>

// Driver code
int main()
{
    // a = 5(00000101), b = 9(00001001)
    unsigned char a = 5, b = 9;

    // The result is 00001010
    printf("a<<1 = %d\n", (a << 1));

    // The result is 00010010
    printf("b<<1 = %d", (b << 1));
    return 0;
}

Output
a<<1 = 10
b<<1 = 18

Applications of Left Shift Operator

  1. Multiplication by Powers of Two: Left shifting a number by n positions is equivalent to multiplying it by 2^n and is much faster than normal multiplication
  2. Efficient Calculations: Used in performance-critical applications where arithmetic operations need to be fast.
  3. Bit Manipulation: Common in low-level programming, such as embedded systems and hardware interfacing.

Right Shift(>>) Operators

Right Shift(>>) is a binary operator that takes two numbers, right shifts the bits of the first operand, and the second operand decides the number of places to shift. In other words, right-shifting an integer “a” with an integer “b” denoted as ‘(a>>b)‘ is equivalent to dividing a with 2^b. 

Syntax

a >> b;

where,

  • a is the integer value to be shifted.
  • b specifies how many positions to shift the bits.

Example: let’s take a=5; which is 101 in Binary Form. Now, if “a is right-shifted by 2i.e a=a>>2 then a will become a=a/(2^2). Thus, a=a/(2^2)=1 which can be written as 01.

right-Shift-in-c-cpp

Example of Right Shift Operator

C++
// C++ Program to demonstrate
// use of right-shift operator
#include <iostream>
using namespace std;

// Driver code
int main()
{
    // a = 5(00000101), b = 9(00001001)
    unsigned char a = 5, b = 9;

    // The result is 00000010
    cout << "a>>1 = " << (a >> 1) << endl;

    // The result is 00000100
    cout << "b>>1 = " << (b >> 1) << endl;

    return 0;
}
C
// C Program to demonstrate
// use of right-shift operator
#include <stdio.h>

// Driver code
int main()
{
    // a = 5(00000101), b = 9(00001001)
    unsigned char a = 5, b = 9;

    // The result is 00000010
    printf("a>>1 = %d\n", (a >> 1));

    // The result is 00000100
    printf("b>>1 = %d", (b >> 1));

    return 0;
}

Output
a>>1 = 2
b>>1 = 4

Applications of Right Shift Operators

  1. Division by Powers of Two: Right shifting a number by n positions is equivalent to dividing it by 2^n and it is very fast.
  2. Efficient Calculations: Used in performance-critical applications for fast division operations.
  3. Bit Manipulation: Useful in extracting specific bits from data, common in data compression and cryptography.

Important Points of Shift Operators

1. The left-shift and right-shift operators should not be used for negative numbers. The result of is undefined behavior if any of the operands is a negative number. For example, results of both 1 >> -1 and 1 << -1 is undefined.

C++
// C++ program to show behaviour of shift operators for
// negative values
#include <iostream>

using namespace std;

int main()
{
    // left shift for negative value
    cout << "2 << -5 = " << (2 << -5) << endl;

    //    right shift for negative value
    cout << "2 >> -5 = " << (2 >> -5) << endl;

    return 0;
}
C
// C program to show behaviour of shift operators for
// negative values
#include <stdio.h>

int main()
{
    // left shift for negative value
    printf("2 << -5 = %d\n", (2 << -5));

    //    right shift for negative value
    printf("2 >> -5 = %d", (2 >> -5));

    return 0;
}

Output
2 << -5 = 0
2 >> -5 = 64

2. If the number is shifted more than the size of the integer, the behavior is undefined. For example, 1 << 33 is undefined if integers are stored using 32 bits. For bit shift of larger values 1ULL<<62  ULL is used for Unsigned Long Long which is defined using 64 bits that can store large values.

C++
//    c++ program to demonstrate the behaviour of bitwise
// shift operators for large values
#include <iostream>

using namespace std;

int main()
{
    int N = 3;

    // left shift by 65 digits
    cout << "3 << 65" << (3 << 65) << endl;

    return 0;
}
C
//    c program to demonstrate the behaviour of bitwise
// shift operators for large values
#include <stdio.h>

int main()
{
    int N = 3;

    // left shift of 65 digits
    printf("3 << 65 = %d", (3 << 65));

    return 0;
}

Output
3 << 65 = 0

3. The left-shift by 1 and right-shift by 1 are equivalent to the product of the first term and 2 to the power given element(1<<3 = 1*pow(2,3)) and division of the first term and second term raised to power 2 (1>>3 = 1/pow(2,3)) respectively. 

C++
// C++ program to get the shifted values using pow()
#include <cmath>
#include <iostream>

using namespace std;

int main()
{
    cout << "2^5 using pow() function" << pow(2, 5) << endl;

    cout << "2^5 using leftshift" << (1 << 5) << endl;

    return 0;
}
C
// C program for the above approach

#include <math.h>
#include <stdio.h>

int main()
{
    printf("2^5 using pow() function: %.0f\n", pow(2, 5));
    printf("2^5 using left shift: %d\n", (1 << 5));
    return 0;
}

// This code is contributed Prince Kumar

Output
2^5 using pow() function: 32
2^5 using left shift: 32

Must Read: Bitwise Operators in C/C++



Similar Reads

Split a Binary String such that count of 0s and 1s in left and right substrings is maximum
Given a binary string, str of length N, the task is to find the maximum sum of the count of 0s on the left substring and count of 1s on the right substring possible by splitting the binary string into two non-empty substrings. Examples: Input: str = "000111" Output: 6 Explanation: Splitting the binary string into "000" and "111". Count of 0s in the
7 min read
What are the differences between bitwise and logical AND operators in C/C++?
A Bitwise And operator is represented as '&amp;' and a logical operator is represented as '&amp;&amp;'. The following are some basic differences between the two operators. a) The logical and operator '&amp;&amp;' expects its operands to be boolean expressions (either 1 or 0) and returns a boolean value. The bitwise and operator '&amp;' work on Inte
4 min read
C++ Increment and Decrement Operators
Prerequisite: Operators in C++ What is a C++ increment Operator? The C++ increment operator is a unary operator. The symbol used to represent the increment operator is (++). The increment operator increases the value stored by the variable by 1. This operator is used for Numeric values only. There are two types of C++ increment Operator: Pre-Increm
4 min read
What are the Operators that Can be and Cannot be Overloaded in C++?
There are various ways to overload Operators in C++ by implementing any of the following types of functions: 1) Member Function 2) Non-Member Function 3) Friend Function List of operators that can be overloaded are: + - * ? % ? &amp; | ~ ! = &lt; &gt; += -= *= ?= %= ?= &amp;= |= &lt;&lt; &gt;&gt; &lt;&lt;= &gt;&gt;= == != &lt;= &gt;= &amp;&amp; ||
4 min read
Conditionally assign a value without using conditional and arithmetic operators
Given 4 integers a, b, y, and x, where x can assume the values of either 0 or 1 only. The following question is asked: If 'x' is 0, Assign value 'a' to variable 'y' Else (If 'x' is 1) Assign value 'b' to variable 'y'. Note: - You are not allowed to use any conditional operator (including the ternary operator) or any arithmetic operator (+, -, *, /)
6 min read
new and delete Operators in C++ For Dynamic Memory
Dynamic memory allocation in C/C++ refers to performing memory allocation manually by a programmer. Dynamically allocated memory is allocated on Heap, and non-static and local variables get memory allocated on Stack (Refer to Memory Layout C Programs for details). What are applications?  One use of dynamically allocated memory is to allocate memory
6 min read
# and ## Operators in C
Stringizing operator (#)The stringizing operator (#) is a preprocessor operator that causes the corresponding actual argument to be enclosed in double quotation marks. The # operator, which is generally called the stringize operator, turns the argument it precedes into a quoted string. It is also known as the stringification operator. It is general
2 min read
reinterpret_cast in C++ | Type Casting operators
reinterpret_cast is a type of casting operator used in C++. It is used to convert a pointer of some data type into a pointer of another data type, even if the data types before and after conversion are different.It does not check if the pointer type and data pointed by the pointer is same or not. Syntax : data_type *var_name = reinterpret_cast &lt;
3 min read
unordered_set operators in C++ STL
Unordered_set provides two operators in C++ STL. These are: Syntax: 1. (unordered_set &amp;lhs == unordered_set &amp;rhs) 2. (unordered_set &amp;lhs != unordered_set &amp;rhs) These operators are discussed in detail below: unordered_set == operator in C++ STL The ‘==’ is an operator in C++ STL performs equality comparison operation between two unor
5 min read
C++ Pointer Operators
Prerequisite: Pointers in C++ A pointer variable is a variable that stores the address of another variable or in other a pointer variable points to the variable whose address is stored inside it. Syntax: int *pointer_name; There are mainly two types of Pointer operators mainly used: Address of operator (&amp;)The indirection operator/Dereference op
2 min read
C++ Arithmetic Operators
Arithmetic Operators in C++ are used to perform arithmetic or mathematical operations on the operands. For example, ‘+’ is used for addition, ‘-‘ is used for subtraction, ‘*’ is used for multiplication, etc. In simple terms, arithmetic operators are used to perform arithmetic operations on variables and data; they follow the same relationship betwe
3 min read
Input/Output Operators Overloading in C++
Operator Overloading is a part of Polymorphism, which enables the feature because of which we can directly use operators with user-defined classes and objects. To read more about this, refer to the article operator overloading in C++. Input/Output Operators(&gt;&gt;/&lt;&lt;) Overloading in C++ We can't directly use the Input/Output Operators (&gt;
2 min read
C++ Comparison Operators
Comparison operators are operators used for comparing two elements, these are mostly used with if-else conditions as they return true-false as result. There are mainly 6 Comparison Operators namely: Greater than (&gt;) : this operator checks whether operand1 is greater than operand2. If the result turns out to be true, it returns true or else retur
3 min read
C++ Relational Operators
In C++ programming language, we sometimes require to compare values and expressions. This comparison allows us to determine relationships, make decisions, and control the flow of our programs. The relational operators in C++ provide the means to compare values and evaluate conditions. In this article, we will learn about C++ relational operators an
4 min read
C++ Logical Operators
In C++ programming languages, logical operators are symbols that allow you to combine or modify conditions to make logical evaluations. They are used to perform logical operations on boolean values (true or false). In C++, there are three logical operators: Logical AND ( &amp;&amp; ) OperatorLogical OR ( || ) OperatorLogical NOT ( ! ) OperatorLet's
4 min read
Unary Operators In C++
Unary operators in C++ are those operators that work on a single value (operand). They perform operations like changing a value's sign, incrementing or decrementing it by one, or obtaining its address. Examples include ++ for increment, -- for decrement, + for positive values, - for negative values,! for logical negation, and &amp; for retrieving m
8 min read
Assignment Operators In C++
In C++, the assignment operator forms the backbone of many algorithms and computational processes by performing a simple operation like assigning a value to a variable. It is denoted by equal sign ( = ) and provides one of the most basic operations in any programming language that is used to assign some value to the variables in C++ or in other wor
7 min read
Increment (Decrement) operators require L-value Expression
What will be the output of the following program? #include&lt;stdio.h&gt; int main() { int i = 10; printf(&quot;%d&quot;, ++(-i)); return 0; } A) 11 B) 10 C) -9 D) None Answer: D, None - Compilation Error. Explanation: In C/C++ the pre-increment (decrement) and the post-increment (decrement) operators require an L-value expression as operand. Provi
1 min read
Order of operands for logical operators
The order of operands of logical operators &amp;&amp;, || are important in C/C++. In mathematics, logical AND, OR, etc... operations are commutative. The result will not change even if we swap RHS and LHS of the operator. In C/C++ (may be in other languages as well)  even though these operators are commutative, their order is critical. For example
1 min read
const_cast in C++ | Type Casting operators
C++ supports following 4 types of casting operators: 1. const_cast 2. static_cast 3. dynamic_cast 4. reinterpret_cast 1. const_cast const_cast is used to cast away the constness of variables. Following are some interesting facts about const_cast. 1) const_cast can be used to change non-const class members inside a const member function. Consider th
4 min read
Overloading stream insertion (&lt;&gt;) operators in C++
In C++, stream insertion operator "&lt;&lt;" is used for output and extraction operator "&gt;&gt;" is used for input. We must know the following things before we start overloading these operators. 1) cout is an object of ostream class and cin is an object of istream class 2) These operators must be overloaded as a global function. And if we want to
2 min read
How to sum two integers without using arithmetic operators in C/C++?
Given two integers a and b, how can we evaluate the sum a + b without using operators such as +, -, ++, --, ...? Method 1 (Using pointers)An interesting way would be: C/C++ Code // May not work with C++ compilers and // may produce warnings in C. // Returns sum of 'a' and 'b' int sum(int a, int b) { char *p = a; return (int)&amp;amp;p[b]; } Despite
4 min read
Written version of Logical operators in C++
Can we use keywords in place of operators in C++ ? Yes, certainly, we can. The ANSI C++ Standard has proposed keywords for several C++ operators . They originated in C in the header at the time when there were keyboards that couldn't type the required symbols like &&, !, || etc. In C++, they became alternate token just like regular tokens, except f
2 min read
Comparing String objects using Relational Operators in C++
If strings are compared using relational operators then, their characters are compared lexicographically according to the current character traits, means it starts comparison character by character starting from the first character until the characters in both strings are equal or a NULL character is encountered. Parameters : Two Strings required t
2 min read
Casting Operators in C++
Casting operators are used for type casting in C++. They are used to convert one data type to another. C++ supports four types of casts: static_castdynamic_castconst_castreinterpret_cast1. static_castThe static_cast operator is the most commonly used casting operator in C++. It performs compile-time type conversion and is mainly used for explicit c
5 min read
Assignment Operators in C
Assignment operators are used for assigning value to a variable. The left side operand of the assignment operator is a variable and right side operand of the assignment operator is a value. The value on the right side must be of the same data-type of the variable on the left side otherwise the compiler will raise an error. Different types of assign
3 min read
Bitwise Operators in C++
There are various Operators present in C++. Every Operator has a particular symbol as well as an Operation to perform. We have various categories of operators in C++. Arithmetic OperatorsRelational OperatorsLogical OperatorsAssignment OperatorsBitwise OperatorsIn this article, we will learn about the Bitwise Operators in C++. C++ Bitwise OperatorsB
6 min read
Operators in C++
An operator is a symbol that operates on a value to perform specific mathematical or logical computations. They form the foundation of any programming language. In C++, we have built-in operators to provide the required functionality. An operator operates the operands. For example,  int c = a + b;Here, '+' is the addition operator. 'a' and 'b' are
13 min read
Conversion Operators in C++
In C++, the programmer abstracts real-world objects using classes as concrete types. Sometimes, it is required to convert one concrete type to another concrete type or primitive type implicitly. Conversion operators play an important role in such situations. It is similar to the operator overloading function in class. In this article, we will learn
4 min read
Bitwise Operators in C
In C, the following 6 operators are bitwise operators (also known as bit operators as they work at the bit-level). They are used to perform bitwise operations in C. The &amp; (bitwise AND) in C takes two numbers as operands and does AND on every bit of two numbers. The result of AND is 1 only if both bits are 1.  The | (bitwise OR) in C takes two n
7 min read
Practice Tags :