Shift the bits of an integer to the right and set the count of shifts as an array with signed integer type in Numpy

NumpyServer Side ProgrammingProgramming

To shift the bits of an integer to the right, use the numpy.right_shift() method in Python Numpy. We have set the count of shifts as a new array. Bits are shifted to the right x2. Because the internal representation of numbers is in binary format, this operation is equivalent to dividing x1 by 2**x2.

The x1 is the Input values. The x2 is the number of bits to remove at the right of x1. If x1.shape != x2.shape, they must be broadcastable to a common shape.

The function right_shift() returns x1 with bits shifted x2 times to the right. 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. The datatype is set using the "dtype" parameter. We have set the datatype to signed integer type −

arrRight = np.array([2, 3, 5],dtype=np.int8)

Displaying our array −

print("Array...\n",arr)

Get the datatype −

print("\nArray datatype...\n",arr.dtype)

Get the dimensions of the Array −

print("\nArray Dimensions...\n",arr.ndim)

Get the shape of the Array −

print("\nOur Array Shape...\n",arr.shape)

Get the number of elements of the Array −

print("\nElements in the Array...\n",arr.size)

The actual integer value −

val = 25

To shift the bits of an integer to the right, use the numpy.right_shift() method. We have set the count of shifts as an array arrRight −

print("\nResult (right shift)...\n",np.right_shift(val, arrRight))

Example

import numpy as np

# Create a One-Dimensional array
# The datatype is set using the "dtype" parameter
# We have set the datatype to signed integer type

arrRight = np.array([2, 3, 5],dtype=np.int8)
# Displaying our array
print("Array...\n",arrRight)

# Get the datatype
print("\nArray datatype...\n",arrRight.dtype)

# Get the dimensions of the Array
print("\nArray Dimensions...\n",arrRight.ndim)

# Get the shape of the Array
print("\nOur Array Shape...\n",arrRight.shape)

# Get the number of elements of the Array
print("\nElements in the Array...\n",arrRight.size)

# The actual integer value
val = 25

# To shift the bits of an integer to the right, use the numpy.right_shift() method in Python Numpy
# We have set the count of shifts as an array arrRight
print("\nResult (right shift)...\n",np.right_shift(val, arrRight))

Output

Array...
[2 3 5]

Array datatype...
int8

Array Dimensions...
1

Our Array Shape...
(3,)

Elements in the Array...
3

Result (right shift)...
[6 3 0]
raja
Updated on 22-Feb-2022 07:12:20

Advertisements