0

i know the mechanics behind from operator OR, but in this case why the output is 7 ? what is behind?

x = int(5)
x = x | 3
print(x)

Thanks.

Mick
  • 67
  • 7

1 Answers1

2

or is different from |. The first one is a logical operator and is mainly used with boolean values, but the second one is called a bitwise operator. It works with the binary values of the operands.

5 = 101 in binary

3 = 011 in binary

The bitwise or i.e. | will perform an or operation of the corresponding bits (1 or 0 = 1, 0 or 1 = 1, 1 or 1 = 1) to get 111 i.e. 7

There's also bitwise and & and bitwise not ~, in case you're curious

Eeshaan
  • 1,557
  • 1
  • 10
  • 22