In Python, they are Bitwise Operators known as Bitwise left shift(<<) and Bitwise right shift(>>).
What are Operators?
Operators are the special symbols used to do arithmetic and logical computations. Operators are used to alter values and variables. The value on which the operator operates is referred to as the Operand.
Python Shift Operators
The shift operators are used to shift(move) the bits of a number to the left or right. The number is then multiplied or divided by two. In shifting operators, there are two types of shifting Processes.
- Bitwise Left Shift.
- Bitwise Right Shift.
Bitwise Left Shift
The Bitwise Left shift shifts/moves the bits of a number to the Left. We use the “left shift”(<<) symbol for this. It multiplies the number of bits by two respectively.
For example, let the number = 3
Its binary form = 0000 0011
0000 0011<<1 bit = 0000 0110 = 6
Example1
Approach:
- Give the number as static input and store it in a variable
- Left Shift 1 bit of the given number and print the result.
- Left Shift 2 bits of the given number and print the result.
- The Exit of the Program.
Below is the implementation:
# Give the number as static input and store it in a variable gvn_numb = 3 # Left Shift 1 bit of the given number and print the result print("The number after left shifting given number by 1 bit:") print(gvn_numb<<1) # Left Shift 2 bits of the given number and print the result print("The number after left shifting given number by 2 bits:") print(gvn_numb<<2)
Output:
The number after left shifting given number by 1 bit: 6 The number after left shifting given number by 2 bits: 12
Bitwise Right Shift
The Bitwise Right Shift shifts/moves the bits of a number to the right. We use the “right shift”(>>) symbol for this. It divides the number of bits by two respectively.
For example, let the number = 3
Its binary form = 0000 0011
0000 0011>>1 bit = 0000 0001 = 1
Approach:
- Give the number as static input and store it in a variable
- Right Shift 1 bit of the given number and print the result.
- Right Shift 2 bits of the given number and print the result.
- The Exit of the Program.
Below is the implementation:
# Give the number as static input and store it in a variable gvn_numb = 3 # Right Shift 1 bit of the given number and print the result print("The number after Right shifting given number by 1 bit:") print(gvn_numb>>1) # Right Shift 2 bits of the given number and print the result print("The number after Right shifting given number by 2 bits:") print(gvn_numb>>2)
Output:
The number after Right shifting given number by 1 bit: 1 The number after Right shifting given number by 2 bits: 0