left_shift() function of numpy module

By applying the numpy.left_shift() function, the bit-pattern of the elements of array one are left-shifted by the number of times the corresponding element in array2 and replaced by the same number of zeros on the right side.

Bitwise Operations Updated 1 Oct 2024 1 min read

Overview

  • The numpy.left_shift() function shifts the bits of the integer or Boolean elements from the first array-like instance by the corresponding element from second array times to the left, replacing the same number of rightmost bits with zero.
  • The effect of above left shift operation is equivalent to multiplying the left integer by two to the power the right integer times.
  • The bitwise left shift operation has its applications in faster multiplication of numbers, in image processing while encoding/decoding of images and in cryptography.

Example

python
# Example Python program that uses the numpy.left_shift()

            # function to multiply the operand1 by 2**operand2

            import numpy

# To convert the ndarrays to binary form

            conv2Binary = lambda x: numpy.binary_repr(x, width=8)

            convert     = numpy.vectorize(conv2Binary)

# Create ndarrays

            a1 = numpy.ndarray(shape = (1, 3), dtype = numpy.int32)

            a2 = numpy.ndarray(shape = (1, 3), dtype = numpy.int32)

a1[0][0] = 10

            a1[0][1] = 20

            a1[0][2] = 30

a2[0][0] = 1

            a2[0][1] = 2

            a2[0][2] = 3

# Do left shift of (a1, a2)

            leftShiftResults = numpy.left_shift(a1, a2)

            print("Array1:")

            print(a1)

print("Array2:")

            print(a2)

print("Array1 in binary:")

            print(convert(a1))

print("Array2 in binary:")

            print(convert(a2))

print("Bit pattern of array1 << array2 :")

            print(convert(leftShiftResults))

print("Array1 in decimal after applying numpy.left_shift(array1, array2):")

            print(leftShiftResults)

Output

Output
Array1:

[[10 20 30]]

Array2:

[[1 2 3]]

Array1 in binary:

[['00001010' '00010100' '00011110']]

Array2 in binary:

[['00000001' '00000010' '00000011']]

Bit pattern of array1 << array2 :

[['00010100' '01010000' '11110000']]

Array1 in decimal after applying numpy.left_shift(array1, array2):

[[ 20  80 240]]