Binary left shift and binary right shift
In Python, there are binary left shift (<<
) and binary right shift (>>
) operations that allow you to shift the bits of an integer value. These operations are performed on integer values and cannot be used with floats. Shifting bits is analogous to multiplying or dividing by powers of two.
When you multiply a number by ten, it is equivalent to shifting all the digits to the left and filling the gap with zeros. For example, 12345
multiplied by 10
becomes 123450
. Similarly, dividing by ten is equivalent to shifting the digits to the right. For instance, 12340
divided by 10
becomes 1234
.
In binary representation, shifting a value one bit to the left is like multiplying it by two, and shifting one bit to the right is like dividing by two. The computer performs these shifts in binary because the base for binary numbers is two. The shift operators in Python, <<
and >>
indicate the direction of the shift.
The left argument of the shift operators is the integer value whose bits are being shifted, while the right argument determines the size of the shift. It's important to note that the shift operations are not commutative.
For instance, 17
shifted right by 1
bit (17 >> 1
) is equivalent to integer division by two, resulting in 8
. On the other hand, shifting 17
left by 2
bits (17 << 2
) is equivalent to multiplying it by 4
, resulting in 68
.
Example
example to demonstrate the binary left shift (<<
) and binary right shift (>>
) operations in Python:
# Binary Left Shift (<<)
x = 5
shifted_left = x << 2
print(shifted_left) # Output: 20
# Binary Right Shift >>
y = 16
shifted_right = y >> 2
print(shifted_right) # Output: 4
In the example above, we have two variables x and y.
Using the binary left shift operator (<<
), we shift the bits of x two positions to the left. This operation effectively multiplies x
by 2
raised to the power of the shift amount (2
), resulting in the value 20
.
Using the binary right shift operator (>>
), we shift the bits of y
two positions to the right. This operation is equivalent to dividing y
by 2
raised to the power of the shift amount (2
), resulting in the value 4
.
These examples showcase how the binary shift operations can be used to efficiently multiply or divide integers by powers of two.