Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the logical right binary shift in python

As revealed by the title, in JavaScript there is a specific operator >>>. For example, in JavaScript we will have the following result:

(-1000) >>> 3 = 536870787  (-1000) >> 3 = -125  1000 >>> 3 = 125  1000 >> 3 = 125 

So is there a certain method or operator representing this >>>?

like image 768
dementrock Avatar asked Apr 29 '11 13:04

dementrock


People also ask

How do you shift binary to the right?

Division. To divide a number, a binary shift moves all the digits in the binary number along to the right and fills the gaps after the shift with 0: to divide by two, all digits shift one place to the right. to divide by four, all digits shift two places to the right.

What is >> and << in Python?

They are bit shift operator which exists in many mainstream programming languages, << is the left shift and >> is the right shift, they can be demonstrated as the following table, assume an integer only take 1 byte in memory.

What does >> mean in Python?

In Python >> is called right shift operator. It is a bitwise operator. It requires a bitwise representation of object as first operand. Bits are shifted to right by number of bits stipulated by second operand. Leading bits as towards left as a result of shifting are set to 0.

Is Python right shift logical or arithmetic?

Actually, Python only has arithmetic right shift; logical right shift would not make sense in the context of Python's unbounded integer type. For logical right shift to be defined, you need to specify the number of bits used to represent an integer.


2 Answers

There isn't a built-in operator for this, but you can easily simulate the >>> yourself:

>>> def rshift(val, n): return val>>n if val >= 0 else (val+0x100000000)>>n ...  >>> rshift(-1000, 3) 536870787 >>> rshift(1000, 3) 125 

The following alternative implementation removes the need for the if:

>>> def rshift(val, n): return (val % 0x100000000) >> n 
like image 103
NPE Avatar answered Oct 04 '22 15:10

NPE


No, there isn't. The right shift in python is arithmetical.

like image 21
Femaref Avatar answered Oct 04 '22 14:10

Femaref