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
?
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
?
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
Python works just as expected.
>>> bin(0b1000 | 0b10001)
'0b11001'
>>> bin(0b11 | 0b1000 | 0b10001)
'0b11011'
But saying
>>> 1000 or 10001
1000
is totally different. That looks at two integers and because first one equals True (not 0) it is returnted. If it wasn't true that would return integer value after or operator. That feature is very handy; in python you can say like this
>>> myvalue =["Hello world"]
>>> myvalue and myvalue[0] or "Empty list"
'Hello world'
>>> myvalue = []
>>> myvalue and myvalue[0] or "Empty list"
'Empty list'
Because empty list equals False in this opeartion.