-1

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

Community
  • 1
  • 1
swg1cor14
  • 1,682
  • 6
  • 25
  • 46
  • 1
    I searched all over stackoverflow for that "duplicate" answer and it never came up – swg1cor14 May 31 '16 at 02:28
  • I googled for bitwise operators in Python to find it - Google still doesn't search non-alphabetic characters very well, for some reason... – MattDMo May 31 '16 at 02:29
  • well i didnt know it was called a bitwise operator. I just searched for operators in python. Thanks though. – swg1cor14 May 31 '16 at 02:30
  • No prob. It's not your fault, you have to already know the answer to find the dupe. Read [this](https://wiki.python.org/moin/BitwiseOperators) for a pretty good intro to bitwise operations. Wikipedia is also good. – MattDMo May 31 '16 at 02:32

2 Answers2

4

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.

Tom Karzes
  • 22,815
  • 2
  • 22
  • 41
  • Thank you for answering what the rest of the equation does. – swg1cor14 May 31 '16 at 02:34
  • I think that last part of the equation is what is dropping my initial zeros. Take a look at my other question. Maybe its related? http://stackoverflow.com/questions/37535905/python-reading-wiegand-dropping-zeros – swg1cor14 May 31 '16 at 02:36
  • Yes, the `&` operator is bitwise-AND. It will zero all bits that are not 1 in both operands. So with an operand of `0xFFFFFF`, it's keeping the low-order 24 bits of the other operand, and forcing the rest to zero. – Tom Karzes May 31 '16 at 02:37
1

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
Moon Cheesez
  • 2,489
  • 3
  • 24
  • 38