-1

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 ?

koukou
  • 65
  • 1
  • 7
  • How is `01000` or `10001` = `1000`. It should be `11001` – Sreeram TP Apr 26 '20 at 06:17
  • Does this answer your question? [Bitwise operation and usage](https://stackoverflow.com/questions/1746613/bitwise-operation-and-usage) – kaya3 Apr 26 '20 at 06:31
  • After reading question a few times more I gave it a upvote to compensate one downvote. There is code example and decent question. It could have been written more understandable though. – ex4 Apr 26 '20 at 06:35

2 Answers2

1

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

Sreeram TP
  • 11,346
  • 7
  • 54
  • 108
0

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.

ex4
  • 2,289
  • 1
  • 14
  • 21