What Does >> mean in Python?

8k Views Asked by At

Someone sent me this equation but I don't understand what it means.

result = ((~c1) >> 1) & 0x0FFFFFF

It has to do with converting the binary from a wiegand reader.

Reference

2

There are 2 best solutions below

3
On BEST ANSWER

The >> operator in Python is a bitwise right-shift. If your number is 5, then its binary representation is 101. When right-shifted by 1, this becomes 10, or 2. It's basically dividing by 2 and rounding down if the result isn't exact.

Your example is bitwise-complementing c1, then right-shifting the result by 1 bit, then masking off all but the 24 low-order bits.

3
On

This statement means:

result =                                # Assign a variable
          ((~c1)                        # Invert all the bits of c1
                 >> 1)                  # Shift all the bits of ~c1 to the right
                        & 0x0FFFFFF;    # Usually a mask, perform an & operator

The ~ operator does a two's complement.

Example:

m = 0b111
x  =   0b11001
~x ==  0b11010      # Performs Two's Complement
x >> 1#0b1100
m ==   0b00111
x ==   0b11001      # Here is the "and" operator. Only 1 and 1 will pass through
x & m #0b    1