Shift the bits of an integer to the left in Numpy

NumpyServer Side ProgrammingProgramming

<p>To shift the bits of an integer to the left, use the <strong>numpy.left_shift()</strong> 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).</p><p>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.</p><h2>Steps</h2><p>At first, import the required library &minus;</p><pre class="result notranslate">import numpy as np</pre><p>Create a 0d array &minus;</p><pre class="result notranslate">arr = np.array(65) </pre><p>Displaying our array &minus;</p><pre class="result notranslate">print(&quot;Array... &quot;,arr)</pre><p>Get the datatype &minus;</p><pre class="result notranslate">print(&quot; Array datatype... &quot;,arr.dtype) </pre><p>Get the dimensions of the Array &minus;</p><pre class="result notranslate">print(&quot; Array Dimensions... &quot;,arr.ndim)</pre><p>Get the shape of the Array &minus;</p><pre class="result notranslate">print(&quot; Our Array Shape... &quot;,arr.shape) </pre><p>Get the number of elements of the Array &minus;</p><pre class="result notranslate">print(&quot; Elements in the Array... &quot;,arr.size)</pre><p>The count of left shift &minus;</p><pre class="result notranslate">valLeft = 2 </pre><p>To shift the bits of an integer to the left, use the numpy.left_shift() method in Python Numpy &minus;</p><pre class="result notranslate">print(&quot; Result (left shift)... &quot;,np.left_shift(arr, valLeft))</pre><h2>Example</h2><pre class="demo-code notranslate language-numpy" data-lang="numpy">import numpy as np # Create a 0d array arr = np.array(65) # Displaying our array print(&quot;Array... &quot;,arr) # Get the datatype print(&quot; Array datatype... &quot;,arr.dtype) # Get the dimensions of the Array print(&quot; Array Dimensions... &quot;,arr.ndim) # Get the shape of the Array print(&quot; Our Array Shape... &quot;,arr.shape) # Get the number of elements of the Array print(&quot; Elements in the Array... &quot;,arr.size) # The count of left shift valLeft = 2 # To shift the bits of an integer to the left, use thennumpy.left_shift() method in Python Numpy print(&quot; Result (left shift)... &quot;,np.left_shift(arr, valLeft))</pre><h2>Output</h2><pre class="result notranslate">Array... 65 Array datatype... int64 Array Dimensions... 0 Our Array Shape... () Elements in the Array... 1 Result (left shift)... 260</pre>
raja
Updated on 17-Feb-2022 10:32:02

Advertisements