Shift the bits of integer array elements to the left in Numpy


To shift the bits of a integer array elements to the left, use the numpy.left_shift() method in Python Numpy. Bits are shifted to the left by appending x2 0s at the right of x1. Since the internal representation of numbers is in binary format, this operation is equivalent to multiplying x1 by 2**x2. The x1 is the Input values. The x2 is the number of zeros to append to x1. Has to be non-negative. If x1.shape != x2.shape, they must be broadcastable to a common shape (which becomes the shape of the output).

The function left_shift() returns x1 with bits shifted x2 times to the left. This is a scalar if both x1 and x2 are scalars.

Steps

At first, import the required library −

import numpy as np

Create a One-Dimensional array −

arr = np.array([56, 87, 23, 92, 81, 98, 45, 98])

Displaying our array −

print("Array...
",arr)

Get the datatype −

print("
Array datatype...
",arr.dtype)

Get the dimensions of the Array −

print("
Array Dimensions...
",arr.ndim)

Get the shape of the Array −

print("
Our Array Shape...
",arr.shape)

Get the number of elements of the Array −

print("
Elements in the Array...
",arr.size)

The count of left shift −

valLeft = 3

To shift the bits of an integer to the left, use the numpy.left_shift() method in Python Numpy −

print("
Result (left shift)...
",np.left_shift(arr, valLeft))

Example

import numpy as np

# Create a One-Dimensional array
arr = np.array([56, 87, 23, 92, 81, 98, 45, 98])

# Displaying our array
print("Array...
",arr) # Get the datatype print("
Array datatype...
",arr.dtype) # Get the dimensions of the Array print("
Array Dimensions...
",arr.ndim) # Get the shape of the Array print("
Our Array Shape...
",arr.shape) # Get the number of elements of the Array print("
Elements in the Array...
",arr.size) # The count of left shift valLeft = 3 # To shift the bits of an integer to the left, use the numpy.left_shift() method in Python Numpy print("
Result (left shift)...
",np.left_shift(arr, valLeft))

Output

Array...
[56 87 23 92 81 98 45 98]

Array datatype...
int64

Array Dimensions...
1

Our Array Shape...
(8,)

Elements in the Array...
8

Result (left shift)...
[448 696 184 736 648 784 360 784]

Updated on: 17-Feb-2022

863 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements