0

Considering the following

>>> a = 10
>>> b = 5

What is the difference between adding the values to c using + or |?

>>> c = a + b
>>> c
15
>>> c = a | b
>>> c
15

I ask this question based on this answer where binary and bitwise operations are used, if that makes any difference.

From the answer linked above:

>>> mon, tue, wed, thu, fri, sat, sun = (pow(2, i) for i in range(7)) 
>>> bin(mon) '0b1'
>>> bin(sun) '0b1000000'

# create range:
>>> x = mon | wed | fri
>>> bin(x) '0b10101'

# check if day is in range:
>>> x & mon
1
>>> x & tue
0
Freemium
  • 450
  • 6
  • 16
  • 3
    In cases where `a` and `b` have no overlapping bits, nothing. `5` is `0101` and `10` is `1010`, so the bitwise or and numerical addition are equal; `15` is `1111`. – jonrsharpe Jan 14 '21 at 14:03
  • 1
    Try `10 | 6`, and you get `14`. It's only in special cases that these two have equal results. – anvoice Jan 14 '21 at 14:05
  • For what reason would `|` be used? I couldn't find anything when searching for the `|` symbol. Or is it interchangeable with `+` in python? – Freemium Jan 14 '21 at 14:07
  • You've just been given an example where `a + b != a | b`. Why would you think they are interchangeable? – chepner Jan 14 '21 at 14:14
  • @chepner it was coincidence that the example I used happened to result in 15 in each case which caused my confusion. I didn't see the 2nd comment but the answers cleared things up – Freemium Jan 14 '21 at 14:20

2 Answers2

4

In order to know the difference between + and | it is better to consider, in the beginning, identical values in the variables.

a = b = 5
print(a + b)
# result is 10
print(a | b)
# result is 5

so in the first, it is a normal addition operation, but in the second, it is a bit-wise OR operation.

5 in the binary system is 101

so a | b = 101 or 101 = 101 = 5 in decimal

if we make b = 2, so b = 10 in binary

So, a | b = 101 or 010 = 111 = 7 in decimal

Nour-Allah Hussein
  • 1,439
  • 1
  • 8
  • 17
1

Well, one's an 'or' operation on the binary representation of the digits -- that's the "|" operator.

The other is +, which adds two numbers (integers in this case).

It just happens that the 'or' operation on 10 and 5 is:

5 = 00101

10= 01010

so the bitwise or gets you: 11111 which is 15

If you do 10 + 6, you get 16. However, 10 | 7 gets you binary 11111 which is 15 as well... `.

mrngbaeb
  • 31
  • 4
  • 1
    Thank you for the explanation, was a coincidence that the result was 15 in both cases which added to my confusion – Freemium Jan 14 '21 at 14:22