Search code examples
python-3.xbitwise-operators

python bitwise operation OR


in python

the result of 1000 or 10001 is 1000

the result of 11 or 1000 or 10001 or 11

How can I get 10001 for 1000 or 10001 and 11001 for 11 or 1000 or 10001 ?


Solution

  • In python you can do logical operations (or, and, not etc) over int.

    To convert a string of binary number to int you can do this,

    int('11', 2)

    Then the binary number 11 will be converted to base 2 int. Hence you will get 3.

    Coming back to your problem,

    You need to preform : 1000 or 10001

    To do this, first convert these binary numbers to int and apply logical or operator over those numbers. It will look like this,

    bin(int('1000', 2) | int('10001', 2)) # '0b11001'
    

    0b in the result above indicate it is a binary string.

    Similarly for 11 or 1000 or 10001,

    bin(int('11', 2) | int('1000', 2) | int('10001', 2)) # 0b11011