Shift the bits of an integer to the right in Numpy

To shift the bits of an integer to the right, use the numpy.right_shift() method in Python Numpy. 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 0d array −

arr = np.array(65)

Displaying our array −

print("Array...<br>",arr)

Get the datatype −

print("\nArray datatype...<br>",arr.dtype)

Get the dimensions of the Array −

print("\nArray Dimensions...<br>",arr.ndim)

Get the shape of the Array −

print("\nOur Array Shape...<br>",arr.shape)

Get the number of elements of the Array −

print("\nElements in the Array...<br>",arr.size)

The count of right shift −

valRight = 2

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

print("\nResult (right shift)...<br>",np.right_shift(arr, valRight))

Example

import numpy as np

# Create a 0d array
arr = np.array(65)

# Displaying our array
print("Array...<br>",arr)

# Get the datatype
print("\nArray datatype...<br>",arr.dtype)

# Get the dimensions of the Array
print("\nArray Dimensions...<br>",arr.ndim)

# Get the shape of the Array
print("\nOur Array Shape...<br>",arr.shape)

# Get the number of elements of the Array
print("\nElements in the Array...<br>",arr.size)

# The count of right shift
valRight = 2

# To shift the bits of an integer to the right, use the numpy.right_shift() method in Python Numpy
print("\nResult (right shift)...<br>",np.right_shift(arr, valRight))

Output

Array...
65

Array datatype...
int64

Array Dimensions...
0

Our Array Shape...
()

Elements in the Array...
1

Result (right shift)...
16
Updated on: 2022-02-17T11:17:34+05:30

192 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements