pythonbinary

Why does XOR with (2 ** 32 - 1) flip all bits of a binary number in Python?


Pretty much as the title states. I want to understand how to use of: (2 ** 32 - 1) and ^ (XOR) flips all 0's to 1's and all 1's to 0's

Using python in the example, (^) is an XOR operator

print(00000000000000000000000000000001 ^ (2 ** 32 - 1))

OUTPUT: 11111111111111111111111111111110

Thanks


Solution

  • You didn't exactly specify it, but for this answer I assume that ** is the "to the power of" operator and ^ is the XOR operator.

    2 ** 32 (2 to the power of 32) is in binary 100000000000000000000000000000000

    minus 1 is then 011111111111111111111111111111111

    The XOR operator sets each bit to 1 that is not equal in the two operands.

    All operations together:

    2**32 = 100000000000000000000000000000000
       -1 = 011111111111111111111111111111111
      
            011111111111111111111111111111111
      XOR   000000000000000000000000000000001
          = 011111111111111111111111111111110
    

    You see that it doesn't depend on how many 0 you have before your numbers, as 0 XOR 0 = 0.

    This XOR operation is effectively a NOT for all numbers that do not exceed 32 bits.